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



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

在每次渲染时,您都会生成一个新的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在每次渲染中所说,组件都是编译的。重新编译样式化的 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)}
             />
         )
   }

发生这种情况是因为您已在 render() 方法中定义了Input。每次更新状态时,都会调用 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 })}
      />
    );
  }
}

最新更新