Javascript React 中的 onChange 不捕获文本的最后一个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33088482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onChange in React doesn't capture the last character of text
提问by reectrix
This is my render function:
这是我的渲染功能:
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
});
}
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?
问题是,当我“保存”一个项目或 console.log 打印输出时,最后一个字符丢失了 - 例如,如果我输入“first”,我会打印出“firs”,并且需要是捕获最后一个字符的另一个关键事件。我试过onKeyUp
- 它不允许我输入任何内容,我也试过onKeyDown
and onKeyPress
,它什么都不输出。这里发生了什么,为什么?我怎样才能让最后一个角色出现?
回答by Michelle Tilley
When are you logging the state? Remember that setState
is asynchronous, so if you want to print the newstate, you have to use the callback parameter. Imagine this component:
你什么时候记录状态?请记住,这setState
是异步的,因此如果要打印新状态,则必须使用回调参数。想象一下这个组件:
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);
}
});
Typing a d
at the end of the input will result in the following being logged to the console:
d
在输入的末尾键入 a将导致以下内容被记录到控制台:
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.
请注意,中间值缺少最后一个字符。这是一个工作示例。
回答by Aman
Since setState() function in asynchronous, I used await.I achieved this using async and await, here is my code
由于异步中的 setState() 函数,我使用了 await。我使用 async 和 await 实现了这一点,这是我的代码
render: function() {
return <div className="input-group search-box">
<input
onChange={(e) => {this.handleTextChange(e)}}
type="text"
value={this.state.text}
className="form-control search-item" />
<span className="input-group-btn"></span>
</div>
}
The handleTextCahnge function:
handleTextCahnge 函数:
handleTextChange = async function(event) {
await this.setState({text: event.target.value});
console.log(this.state.text);
}
回答by Taohidul Islam
setState() function in asynchronous. Without using callback you can use another auxiliary variable to store and use the updated value immediately. Like :
异步中的 setState() 函数。在不使用回调的情况下,您可以使用另一个辅助变量来立即存储和使用更新的值。喜欢 :
export default class My_class extends Component{
constructor(props)
{
super(props):
this.state={
text:"",
};
this.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>
}
handleTextChange: function(event) {
console.log(event.target.value);
this.text = event.target.value;
this.setState({
text: event.target.value
});
}
You will get your updated value in this.text variable immediately. But you should use this.state.text to show text in your UI.
您将立即在 this.text 变量中获得更新的值。但是您应该使用 this.state.text 在您的 UI 中显示文本。
回答by Filat Astakhov
Since React v. 16.8you can use react hooks.
从React v. 16.8 开始,你可以使用 react hooks。
import React, { useState } from 'react';
const MyComponent = () => {
const [userInput, setUserInput] = useState("");
const changeHandler = (e) => {
setUserInput(e.target.value);
}
return (
<div>
<input onChange={changeHandler} value={userInput}></input>
</div>
)
}
It works great for me.
这对我很有效。