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

jjb*_*kir 6 javascript reactjs styled-components

当使用带有样式组件的 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 })}
      />
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Den*_*ash 13

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

Run Code Online (Sandbox Code Playgroud)