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

IT技术 javascript reactjs styled-components
2021-05-21 11:51:13

当使用带有样式组件的 html 输入并保存值以使用 onChange 响应状态时,组件似乎在每次状态更改时重新渲染并导致输入失去焦点。有什么办法可以防止输入失去焦点?为什么会出现这种情况?这是一个例子

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个回答

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

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

发生这种情况是因为您已经Inputrender()方法中进行了定义每次更新状态时,render()都会调用方法并Input重新定义和处理,就好像它是一个全新的组件(<input/>在这种情况下是一个没有焦点的 html )。如果您将 的定义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 })}
      />
    );
  }
}