use*_*459 9 javascript reactjs
我试图将我的React类转换为ES6,但是我在这个过程中遇到了一些困难.我想在构造函数中创建绑定,而不是在渲染视图中.
现在,如果我有一个带有setState的根模块,需要一个参数,例如:
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood(value) = this.updateMood.bind(this,value);
}
updateMood(value) {
this.setState({mood: value});
}
Run Code Online (Sandbox Code Playgroud)
然后我将此函数传递给组件:
<customElement updateMood={this.updateMood}></customElement>
Run Code Online (Sandbox Code Playgroud)
然后在customElement模块中,我有这样的事情:
constructor() {
super();
}
update(e) {
this.props.updateMood(e.target.value);
}
Run Code Online (Sandbox Code Playgroud)
在渲染中:
<input onChange={this.update} />
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?因为我不能让它工作;-(
你不能使用这种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>
}
}
Run Code Online (Sandbox Code Playgroud)