【问题标题】:Trigger onblur event on click of enter keypress in React js在React js中点击回车键触发onb​​lur事件
【发布时间】:2019-10-06 14:21:34
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs input focus


    【解决方案1】:

    使用refs 和this.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' />

    【讨论】:

    【解决方案2】:

    使用检测keyCode 事件的onKeyDown 而不是onKeyPress。

    <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
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-12
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      相关资源
      最近更新 更多