0
如何在句子结束时检测输入更改。 当我使用onChange时,状态实时变化,但我想在句子结束或几秒钟后更改状态。转到下一个输入时反应事件触发
如何在句子结束时检测输入更改。 当我使用onChange时,状态实时变化,但我想在句子结束或几秒钟后更改状态。转到下一个输入时反应事件触发
这里有两种解决方案,解决方案之一是监听输入上的按键事件,并且只会在按下句点或回车键时更新状态。如果您将注意力集中在输入之外,解决方案二只会更新状态。点击链接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'));
也许你应该试着去'onFocusOut'? –
使用'onBlur'而不是'onChange' –
@RishabhMishra不,我想在焦点输入时忽略事件“仅”。 – Sepehr