Reputation: 3
I'm workin with react components and es6. How should I use logic from onChange method into other method?
render() {
let input;
return (
<tr> <input
ref = {node => { input = node; }}
onChange = { event => {
if (input.value === this.props.word.pl)
event.currentTarget.style.backgroundColor = 'Chartreuse';
else if (input.value !== this.props.word.pl)
event.currentTarget.style.backgroundColor = 'LightCoral';
else if (input.value === "")
event.currentTarget.style.backgroundColor = 'none';
}
}/>
Upvotes: 0
Views: 1968
Reputation: 1118
Leo, gave you an example of how to bind your methods in the constructor. But I will give you one more example on how can you avoid binding in the constructor.
Arrow functions syntax:
handleChange = e => { ... }
Upvotes: 2
Reputation: 20027
Move your function out on a component level
Bind this in the constructor
Use it on multiple onChange events
class MyComponent extends React.Component {
constructor(props) {
super(props);
// bind this
this.handleChange = this.handleChange.bind(this);
}
// reusable function
handleChange(e) {
// ... your logic for onChange here
}
render() {
return (
<div>
<input onChange={this.handleChange} />
<input onChange={this.handleChange} />
</div>
);
}
};
Read more about React forms here.
Upvotes: 3