样式化组件输入失去了对变化的关注 [英] Styled component input loses focus onChange

查看:28
本文介绍了样式化组件输入失去了对变化的关注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

在每次渲染时,您都会生成一个新的 Input 因此失去焦点.

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

将样式与组件解耦:

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

这篇关于样式化组件输入失去了对变化的关注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆