确保输入值是reactjs中的字母串

Ensure that input value is string of alphabets in reactjs

我正在开发一个 reactjs 应用程序,我希望我的用户必须在输入字段中仅输入字母。 这是我的代码。

<input value= {this.state.val} onChange = {this.handleVal}/>


handleVal = (e)=>{
      this.setState({
      val:e.target.value
      })
}


state = {
  val:''
}

我的组件有很多代码,但我只输入了相关的。 提前致谢。

您可以使用正则表达式测试,只有在 onChange 处理程序上通过测试时才更新输入状态

/^[a-zA-Z]*$/

onChange 处理程序中的用法

  handleVal = (e) => {
    const value = e.target.value;
    const regMatch = /^[a-zA-Z]*$/.test(value);

    if (regMatch) {
        this.setState({
            val: value
        })
    }
  };

您可以使用 onKeyPress 方法,它会避免输入任何其他字母。

 <input placeholder="Enter Alphabets only" onKeyPress={this.onKeyPress} onChange={this.onChange} />

onKeyPress = (event) => {
   if((event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && 
     event.charCode < 123)){
        return true;
   }
      return false;
}

onChange =  (e) => {
  console.log('_________', e.target.value);
  this.setState({
      value: e.target.value
  })
}