转到下一个输入时反应事件触发

时间:2017-07-15 14:05:33

标签: javascript reactjs redux

句子结束时如何检测输入变化。 当我使用onChange时,状态会实时更改,但我希望在句子结束或几秒钟后更改状态。

1 个答案:

答案 0 :(得分:1)

这里有两个解决方案,解决方案一个侦听输入上的键上事件,并且只有在按下句号或输入键时才更新状态。如果您从输入中聚焦,解决方案二只会更新状态。单击CodePen链接以查看两个解决方案的运行示例:https://codepen.io/w7sang/pen/zzbQzQ?editors=1111

// App
class App extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      sentence: null
    }
    this.handleKeyUp = this.handleKeyUp.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
  }
  handleKeyUp(evt) {
    if (evt.keyCode === 190 || evt.keyCode === 13) {
      this.setState({
        sentence: evt.target.value
      });
    }
  }
  handleBlur(evt) {
    this.setState({
      sentence: evt.target.value
    })
  }
  render(){
    return(
      <div>
        <h5>Sentence: (Start typing on any of the solution inputs)</h5>
        {this.state.sentence}
        <div>
          <h5>Solution 1: On KeyUp (To update state, you must press period `.` or enter)</h5>
          <input onKeyUp={this.handleKeyUp} />
        </div>
        <div>
          <h5>Solution 2: On Blur</h5>
          <input onBlur={this.handleBlur} />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<App />,document.getElementById('app'));

相关问题