请考虑以下代码.我想保持文本字段中文本的最后一个字符存储在一个名为的状态lastChar.为此,我做了以下代码?
define(["react","react-keydown"], (React,keydown) => {
var TypingContainer = React.createClass({
getInitialState: function() {
return {text: '',lastChar:''};
},
handleChange: function(e) {
console.log('lastChar typed is:'+ e.target.value.slice(-1));
this.setState({lastChar: e.target.value.slice(-1)});
console.log('lastChar in state is:'+ this.state.lastChar);
}
,
render: function() {
return(
<div>
{this.props.candidateWord}
{this.props.message}
<input
className="typing-container"
value={this.state.message}
onChange={this.handleChange}
/>
</div>
);
}
})
return TypingContainer;
});
Run Code Online (Sandbox Code Playgroud)
例如,如果用户输入hello,我希望看到两者中的最后一个字符,e.target.value.slice(-1)并且this.state.lastChar相同o
同时lastChar显示l
换句话说,lastChar在精确值之前总是一个char?
为什么会这样?我该如何解决?
Ved*_*Ved 10
在调用setState()之后,您将无法获得状态的更新值.这是因为一旦setState()调用视图就会重新渲染.因此最好检查渲染中的更新值.
render: function() {
console.log('lastChar in state is:'+ this.state.lastChar);
return(
<div>
{this.props.candidateWord}
{this.props.message}
<input
className="typing-container"
value={this.state.message}
onChange={this.handleChange}
/>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
要么,
this.setState({
lastChar: e.target.value.slice(-1)}, ()=> {
console.log(this.state.lastChar)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6046 次 |
| 最近记录: |