I've been using React for a few months now, and one of the things I'm finding most difficult is how to properly bind functions that take arguments.
Currently, I have three inputs that share a single update function, but require a different first argument to be passed. Here is my component:
class MyComponent extends Component {
render() {
const { onChange } = this.props;
return(
<div className='my_component'>
<Row>
<Column>
<Input
value={item1}
onChange={ (newValue) => onChange('item1', newValue) } />
</Column>
</Row>
<Row>
<Column>
<Input
value={item2}
onChange={ (newValue) => onChange('item2', newValue) } />
</Column>
</Row>
<Row>
<Column>
<Input
value={item3}
onChange={ (newValue) => onChange('item3', newValue) } />
</Column>
</Row>
</div>
);
}
}
So, currently, I'm using arrow functions in my render function of the component. But through research, I've found that obviously has performance issue in terms of re-rendering.
The solution offered is to bind in the constructor using
constructor() {
super();
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
this.props.onChange('ARGUMENT REQUIRED!', event.target.value);
}
The problem is, that I cannot get that first argument to work... Am I supposed to create a function for each and bind one for each in the constructor, like so:
constructor() {
super();
this.handleItem1Change= this.handleItem1Change.bind(this)
this.handleItem2Change= this.handleItem2Change.bind(this)
this.handleItem3Change= this.handleItem3Change.bind(this)
}
handleItem1Change(newValue) {
this.props.onChange('item1', newValue);
}
handleItem2Change(event) {
this.props.onChange('item2', newValue);
}
handleItem3Change(event) {
this.props.onChange('item3', newValue);
}
That seems repetitive...is there a more streamlined way to do this?
newValueis passed from the input callback, and I messed up theevent.target.valuethat is was is passed up, so it is just the new value. That is relatively irrelevant to the problem at hand, though.