我想要实现的目标:将数据从子级传递给父级。
我如何实现它:使用this.state
如上所述here
不知道如何表达标题:当我 console.log(this.state)
在我修改状态的函数中,this.state
中的正确值被打印出来。但是,当我尝试读取另一个函数中的状态时,this.state
显然仍为空值。
constructor(props) {
super(props);
this.state = {
titleInputValue: "",
};
}
<form onSubmit={this.handleSubmit.bind(this)}>
<TextInput
val={this.state.titleInputValue}
changeHandler={this.textInputChangeHandler} />
</form>
// This is the function which can apparently only get the initial state
// title and body are empty strings, they should have values
handleSubmit(event) {
event.preventDefault();
const title = this.state.titleInputValue;
const body = this.state.bodyInputValue;
console.log(this.state);
Meteor.call('stories.insert',title,body);
}
// However, here the state is retrieved just fine.
// This is the function the child calls to update the state.
textInputChangeHandler(event) {
// This console.log call shows the correct state!
console.log(this.state);
this.setState({
titleInputValue: event.target.value,
});
}
TextInput
具有属性onChange={this.props.changeHandler.bind(this)}
举例说明:
我写了asd
,并在 textInputChangeHandler
中成功检索到状态,这是前两个 console.log
调用,但 handleSubmit
中为空.
最佳答案
这是因为事件处理程序范围不是组件类级别。当您的组件处理事件时,它的上下文是组件(在您的例子中是 TextInput )而不是父组件。
您必须将该函数绑定(bind)到 Component 类范围的 this 上:
<TextInput
val={this.state.titleInputValue}
changeHandler={this.textInputChangeHandler.bind(this) } />
使用 JavaScript 绑定(bind),您还可以指定函数上下文。
关于javascript - React - 状态不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364432/