I have two functions that look like this:
primaryImageLoaded () {
this.setState({primaryImageLoaded: true})
}
secondaryImageLoaded () {
this.setState({ secondaryImageLoaded: true })
}
They are called like this(using react):
onLoad={this.secondaryImageLoaded.bind(this)
This feels excessive and I would like to have just one function and pass the state-variable as a parameter, but how can I pass an additional argument to .bind
? and is it possible to use a variable as key in the object i'm passing to setState
?
You can pass additional arguments to bind that will be passed when your function is invoked:
this.secondaryImageLoaded.bind(this, arg1, arg2)
If you are using ECMAScript 2015 and onwards, you can use a variable as a key by wrapping it in square brackets:
this.setState({
[myVar]: value
});
So you could rewrite it to be more like:
function imageLoaded(which) {
this.setState({
[which]: true
});
}
onLoad={this.imageLoaded.bind(this, 'secondary')}
You can use arrow function for definition your function, and this way you don't need bind method.
secondaryImageLoaded = () => {
this.setState({ secondaryImageLoaded: true })
}
After that, in your jsx code:
onLoad={this.secondaryImageLoaded}
If you want know more about that you read this article
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