反应按键输入

问题描述 投票:5回答:2

我试图阻止一些角色被输入,但由于某种原因,禁令不会发生。我哪里错了?

render () {
    return <form>
        <input
            id="username"
            type="text"
            placeholder="Username"
            value={this.state.value}
            onKeyPress={this.pale_username.bind(this)}
        />
    </form>
}

和功能

pale_username(key) {
    if((key.charCode < 48 || key.charCode > 57) //numbers
        && (key.charCode < 65 || key.charCode > 90) // AB
        && (key.charCode < 97 || key.charCode > 122) // ab
        && (key.charCode !== 36) // $
        && (key.charCode !== 38) // &
        && (key.charCode < 40 || key.charCode > 41) // ()
        && (key.charCode < 45 || key.charCode > 46) // -.
        && (key.charCode !== 95) // _
        && (key.charCode !== 127) // del
        && (key.charCode !== 8) // BackSpace
        && (key.charCode !== 46))
        return false;
}
reactjs function keypress onkeypress
2个回答
1
投票

我会在onChange处理程序中处理字符'ban'。一个原因是,如果有人在输入中复制并粘贴某些内容会发生什么?防止键盘事件处理程序中的输入将不起作用。

我会尝试这样的事情:

handleChange(e) {
  // Use whatever regex you need.
  const filteredInput = e.target.value.replace(/[abAB$&()-_.*]|\d+/g, '');
  this.setState(value: filteredInput)
}

然后在输入中使用它。

<input
  id="username"
  type="text"
  placeholder="Username"
  value={this.state.value}
  onChange={this.handleChange.bind(this)}
/>

0
投票

qazxsw poi检测到qazxsw poi和qazxsw poi检测到onKeyDown。尝试将其更改为charCode

© www.soinside.com 2019 - 2024. All rights reserved.