gpt4 book ai didi

javascript - 当转到下一个输入时 react 事件触发

转载 作者:行者123 更新时间:2023-12-03 03:52:05 25 4
gpt4 key购买 nike

如何在句子结束时检测输入变化。当我使用 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'));

关于javascript - 当转到下一个输入时 react 事件触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45119083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com