在React JS中单击Enter键时触发onb​​lur事件

时间:2019-05-20 08:36:26

标签: javascript reactjs input focus

我有一个输入文本字段。当用户输入任何文本并单击Enter按钮时,我需要激活blur事件以移除焦点并验证textinput。

<input style={{marginTop:'20%', marginLeft:'40%'}} value={value} type="text" onFocus={onFocus} onChange={e => setValue(e.target.value)}  onKeyPress={handleKeyPress}/>

2 个答案:

答案 0 :(得分:1)

使用onKeyPress来检测onKeyDown事件,而不是keyCode

<input style={{marginTop:'20%', marginLeft:'40%'}} value={value} type="text" onFocus={onFocus} onChange={e => setValue(e.target.value)}  onKeyDown={(e) => this.handleKeyPress(event)}/>

函数将类似于

handleKeyPress(e){
   if(e.keyCode === 13){
     e.target.blur(); 
     //Write you validation logic here
   }
}

答案 1 :(得分:1)

使用refsthis.inputRef.current.blur()。这是可行的解决方案。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      value: ""
    };
  }
  keypressHandler = event => {
    if (event.key === "Enter") {
      this.setState({ value: this.inputRef.current.value });
      this.inputRef.current.blur();
      this.inputRef.current.value = "";
    }
  };
  render() {
    return (
      <div>
      <label>Enter Text</label>
        <input
          type="text"
          ref={this.inputRef}
          onKeyPress={event => this.keypressHandler(event)}
        />
        <p>{this.state.value}</p>
      </div>
    );
  }
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />