【问题标题】:Styled component input loses focus onChange样式化的组件输入失去焦点 onChange
【发布时间】:2019-11-27 12:43:54
【问题描述】:

当使用带有 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 })}
      />
    );
  }
}

【问题讨论】:

  • styled.input 创建一个新的合法反应组件。它应该在MyComponent 之外定义。如果您打算专门为特定 input 定义样式而不定义单独的组件,请考虑使用 css prop

标签: javascript reactjs styled-components


【解决方案1】:

在每次渲染时,您都会生成一个新的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 })}
      />
    );
  }
}

【讨论】:

    【解决方案2】:

    发生这种情况是因为您在 render() 方法中定义了 Input。每次状态更新时,render() 方法将被调用,Input 将被重新定义和处理,就好像它是一个全新的组件(在这种情况下是一个没有焦点的 html &lt;input/&gt;)。如果将Input 的定义移出组件,它将按预期工作。此外,您在 render() 方法的返回中使用的片段 (&lt;/&gt;) 有点毫无意义。

    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 })}
          />
        );
      }
    }
    

    【讨论】:

      【解决方案3】:

      正如@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)}
                   />
               )
         }
      

      【讨论】:

        猜你喜欢
        • 2018-12-20
        • 1970-01-01
        • 2023-03-26
        • 2017-09-17
        • 1970-01-01
        • 2020-05-23
        • 2019-05-15
        • 2021-12-14
        • 1970-01-01
        相关资源
        最近更新 更多