Styled component input loses focus onChange

左心房为你撑大大i 提交于 2019-11-28 10:55:43

问题


When using an html input with styled-components and saving the value to react state with onChange, the component appears to be re-rendering on every state change and causing the input to lose focus. Is there any way to prevent the input from losing focus? Why is this occurring? 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 })}
      />
    );
  }
}

回答1:


On every render, you generate a new Input therefore loss of focus.

Decouple the style from the component:

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:


This happens because you've defined Input within the render() method. Every time the state gets updated, the render() method will be called and Input will be redefined and handled as if it was a completely new component (a html <input/> without focus in this case). If you move the definition of Input out of the component, it will work as intended. Also the fragment you've used (</>) in the return of the render() method is kind of pointless.

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


来源:https://stackoverflow.com/questions/57096907/styled-component-input-loses-focus-onchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!