I am trying to convert my React classes to ES6, but I am having some difficulty within this process.. I would like to have my bindings in the constructor, not in the render view.
Now, if I have a root module with a setState which needs a parameter, e.g.:
constructor() {
super();
this.state = {
mood: ""
};
this.updateMood(value) = this.updateMood.bind(this,value);
}
updateMood(value) {
this.setState({mood: value});
}
Then I pass this function to a component:
<customElement updateMood={this.updateMood}></customElement>
Then within the customElement module, I have something like this:
constructor() {
super();
}
update(e) {
this.props.updateMood(e.target.value);
}
and in the render:
<input onChange={this.update} />
Is this the correct way? Since I can't get it to work ;-(
You can't use this this.updateMood(value) = this.updateMood.bind(this,value);
construction, because it is syntax error.
You can solve your problem like this
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>
}
}
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With