Reputation: 3391
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 ;-(
Upvotes: 9
Views: 13501
Reputation: 4978
Or, depending on your babel settings, or when using typescript, the following achieves the same but is a lot more convenient to write / maintain:
class Parent extends React.Component {
constructor() {
super();
this.state = {
mood: ""
};
}
updateMood = (value) => {
this.setState({ mood: value });
}
}
Upvotes: 0
Reputation: 77482
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>
}
}
Upvotes: 7