反应输入类型编号Onchange速度很慢



我想设置一个输入,用户可以使用REGEX。

// component A
<Input
    name="password"
    value={this.props.password}
    onChange={this.props.onChange}
/>

// component B
state = { password : '' }
handleChange = (e) => {
   const value = e.target.value;
   const regexAllowOneDot = /d+(.?d{0,8})/;
   if(regexAllowOneDot.exec(value) !== null) {
        this.setState({
            password: regexAllowOneDot.exec(value)[0]
        })
    }else {
        this.setState({
            password: ''
        })
   }
}

<ComponentA
   password={this.state.password}
   onChange={this.handleChange}
/>

当输入的类型为"文本"时,它起作用,但是当类型为" number"。

所以,当类型为"数字"时,我在下面得到这些问题(但是,当类型为"文本"时,这些问题是完全解决的)

  1. 当我从Chrome检查开发人员工具时,输入的值不会更改(但是E.Target.Value Works)

  2. 另外,当我检查 console.log(regexAllowOneDot.exec(value)[0])时,即使值仍然具有一个数字(如1或2或...)

我想知道为什么以及如何解决此问题或是否有更好的解决方案。

好吧,我现在明白了。您想处理按键事件并在必要时停止,例如:

keyPress = e => {
  if (e.which === 46 && this.state.amount.includes(".")) {
    e.preventDefault();
    e.stopPropagation();
  }
};

然后将功能向下传递到子组件并将其连接到Onkeypress。

我在此处解决了您的代码的工作叉:

最新更新