Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass additional parameters to bind?

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?

like image 389
Himmators Avatar asked Dec 23 '16 16:12

Himmators


2 Answers

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')}
like image 190
ray hatfield Avatar answered Oct 11 '22 14:10

ray hatfield


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

like image 29
Zahra Mirzaei Avatar answered Oct 11 '22 14:10

Zahra Mirzaei