React中的onChange不捕获文本的最后一个字符 [英] onChange in React doesn't capture the last character of text
问题描述
这是我的渲染功能:
render: function() {
return <div className="input-group search-box">
<input
onChange={this.handleTextChange}
type="text"
value={this.state.text}
className="form-control search-item" />
<span className="input-group-btn"></span>
</div>
}
我将此作为我的事件处理程序:
and I have this as my event handler:
handleTextChange: function(event) {
console.log(event.target.value);
this.setState({
text: event.target.value
});
}
问题是当我保存某个项目或者console.log时打印输出,最后一个字符丢失 - 例如,如果我输入first,我将打印出firs,并且需要另一个关键事件来捕获最后一个字符。我已经尝试了 onKeyUp
- 这不允许我输入任何内容,我也尝试了 onKeyDown
和 onKeyPress
,什么都不输出。
这里发生了什么,为什么?我怎样才能让最后一个角色出现?
The problem is that when I "save" an item, or console.log print the output, the last character is missing - for instance, if I enter "first", I'll get "firs" printed out, and there needs to be another key event to capture the last character. I've tried onKeyUp
- which doesn't let me type anything in, and I've also tried onKeyDown
and onKeyPress
, which output nothing.
What is happening here and why? and how can I get that last character to show up?
推荐答案
您何时登录该州?请记住, setState
是异步的,因此如果要打印 new 状态,则必须使用callback参数。想象一下这个组件:
When are you logging the state? Remember that setState
is asynchronous, so if you want to print the new state, you have to use the callback parameter. Imagine this component:
let Comp = React.createClass({
getInitialState() {
return { text: "abc" };
},
render() {
return (
<div>
<input type="text" value={this.state.text}
onChange={this.handleChange} />
<button onClick={this.printValue}>Print Value</button>
</div>
);
},
handleChange(event) {
console.log("Value from event:", event.target.value);
this.setState({
text: event.target.value
}, () => {
console.log("New state in ASYNC callback:", this.state.text);
});
console.log("New state DIRECTLY after setState:", this.state.text);
},
printValue() {
console.log("Current value:", this.state.text);
}
});
在结尾处输入 d
输入将导致以下内容被记录到控制台:
Typing a d
at the end of the input will result in the following being logged to the console:
Value from event: abcd
New state DIRECTLY after setState: abc
New state in ASYNC callback: abcd
请注意中间值缺少最后一个角色这是一个有效的例子。
Notice that the middle value is missing the last character. Here's a working example.
这篇关于React中的onChange不捕获文本的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!