我正在尝试将我的 React 类转换为 ES6,但在此过程中我遇到了一些困难。我希望将我的绑定(bind)放在构造函数中,而不是渲染 View 中。
现在,如果我有一个带有 setState 的根模块,它需要一个参数,例如:
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood(value) = this.updateMood.bind(this,value);
}
updateMood(value) {
this.setState({mood: value});
}
然后我将这个函数传递给一个组件:
<customElement updateMood={this.updateMood}></customElement>
然后在 customElement 模块中,我有这样的东西:
constructor() {
super();
}
update(e) {
this.props.updateMood(e.target.value);
}
在渲染中:
<input onChange={this.update} />
这是正确的方法吗?因为我无法让它工作 ;-(
最佳答案
你不能使用这个 this.updateMood(value) = this.updateMood.bind(this,value);
结构,因为它是语法错误。
你可以这样解决你的问题
class CustomElement extends React.Component {
constructor() {
super();
this.update = this.update.bind(this);
}
update(e) {
this.props.updateMood(e.target.value);
}
render() {
return <input onChange={this.update} />
}
}
class Parent extends React.Component {
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood = this.updateMood.bind(this);
}
updateMood(value) {
this.setState({ mood: value });
}
render() {
return <div>
<CustomElement updateMood={this.updateMood}></CustomElement>
<h1>{ this.state.mood }</h1>
</div>
}
}
关于javascript - 在构造函数中 react 绑定(bind),如何将参数传递给 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412247/