[英]Why does input setState inside setTimeout break Chinese IME?
I have a simple controlled input component in React and I am trying to wrap my head around this behavior. 我在React中有一个简单的受控输入组件,我正在设法解决这个问题。
If I do it the normal way, everything works fine and Chinese IME works as expected: 如果我以正常方式进行操作,则一切正常,并且IME可以按预期工作:
<input
type="text"
value={this.state.value}
onChange={(event) => {
this.setState({ value: event.target.value });
}}
/>
But if I wrapped a setTimeout or another setState outside, Chinese IME does not work anymore, it seems like it's been interrupted during each setState? 但是,如果我将setTimeout或另一个setState包装在外面,则中文IME将不再起作用,似乎在每个setState期间它都已中断?
# setTimeout
<input
type="text"
value={this.state.value}
onChange={(event) => {
const value = event.target.value;
setTimeout(() => {
this.setState({ value });
}, 0);
}}
/>
# another setState
<input
type="text"
value={this.state.value}
onChange={(event) => {
const value = event.target.value;
this.setState({ isTyping: true }, () => {
this.setState({ value });
});
}}
/>
I am not looking for the correct way to make Chinese IME work, I just find it very interesting and want to understand what causes this behavior. 我不是在寻找使中文IME工作的正确方法,我只是觉得它很有趣并且想了解是什么原因导致了这种行为。 I sort of understand there's an "update loop" for each setState operation but I am not sure how that would break the Chinese IME.
我有点理解每个setState操作都有一个“更新循环”,但是我不确定这将如何破坏中文IME。 Is this related to event loop and how setTimeout pushes the operation to the back of the queue?
这是否与事件循环有关,以及setTimeout如何将操作推送到队列的后面?
Many thanks! 非常感谢!
Try this. 尝试这个。 You are not recommended to do setTimeout in user input event handler function.
不建议在用户输入事件处理程序函数中执行setTimeout。 Don't use setTimeout of setting state
不要使用设置状态的setTimeout
handleChange = event = > {
const value = event.target.value;
this.setState({ value });
}
<input
type="text"
value={this.state.value}
onChange={event => this.handleChange(event)}
/>
Even if it is 0 milliseconds setTimeout will delay setting user input. 即使是0毫秒,setTimeout也会延迟设置用户输入。 Check below thread for more details about using setTimeout with zero milliseconds
检查以下线程以获取有关使用零毫秒的setTimeout的更多详细信息
I checked your code amd I didn't found any issue on your code.
My react version is 16.6 and your code work fine on my machine.
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
}
}
onClick() {
this.setState({ showLazy: !this.state.showLazy });
}
render() {
return (<div>
<input
type="text"
value={this.state.value}
onChange={(event) => {
const value = event.target.value;
this.setState({ isTyping: true }, () => {
this.setState({ value });
});
}}
/>
<input
type="text"
value={this.state.value}
onChange={event => {
const value = event.target.value;
setTimeout(() => {
this.setState({ value })
}, 0);
}}
/>
</div>)
}
}
export default AdvanceApp; 导出默认的AdvanceApp;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.