样式化的组件输入失去了对变更的关注

时间:2019-07-18 14:28:06

标签: javascript reactjs styled-components

当使用带有styled-components的html输入并通过onChange保存值以响应状态时,该组件似乎在每次状态更改时都重新呈现,并导致输入失去焦点。有什么办法可以防止输入失去焦点?为什么会这样呢? Here is an example

class MyComponent extends React.Component {
  state = { val: "" };

  render() {
    const Input = styled.input`
      border-radius: 6px;
    `;

    return (
      <Input
        value={this.state.val}
        onChange={e => this.setState({ val: e.target.value })}
      />
    );
  }
}

3 个答案:

答案 0 :(得分:0)

在每个渲染上,您都会生成一个新的Input,因此会失去焦点。

将样式与组件分离:

const Input = styled.input`
  border-radius: 6px;
`;

class MyComponent extends React.Component {
  state = { val: "" };

  render() {
    return (
      <Input
        value={this.state.val}
        onChange={e => this.setState({ val: e.target.value })}
      />
    );
  }
}

答案 1 :(得分:0)

发生这种情况是因为您已经在Input方法中定义了render()。每次状态更新时,都将调用render()方法,并将Input重新定义和处理,就好像它是一个全新的组件一样(在这种情况下,HTML <input/>无需关注) 。如果将Input的定义移出组件,它将按预期工作。同样,您在</>方法的返回中使用的片段(render()也毫无意义。

const Input = styled.input`
  border-radius: 6px;
`;

class MyComponent extends React.Component {
  state = { val: '' };

  render(){
    return(
      <Input
        value={this.state.val}
        onChange={e => this.setState({ val: e.target.value })}
      />
    );
  }
}

答案 2 :(得分:0)

就像@Dennis Vash在每个渲染中所说的那样,将对组件进行编译。使用链接重新编译Styled-CSS到组件。 同样,如果您在函数中使用了样式化的组件。将其复制粘贴到函数外部,以使变量仅创建一次

    const CustomInput = styled.input`
       border:none;
       border-radius:0px;
       padding:2px 11px;
       border-bottom:1px solid #ced4da;
       &:focus {
         outline: none;
         border-color:#ced4da;
       }
   `;

   function myFun(props){
         const [value, setvalue] = useState('')
         return (
             <CustomInput 
                value={value}
                onChange={(e)=>setvalue(e.target.value)}
             />
         )
   }
相关问题