Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding this.method.bind(null,...) in ReactJS?

I am working through examples learning ReactJS (Mastering React). While recreating examples, I am clueless with couple of statements and would appreciate some help.

Fiddle: Composing Components

First

...
//Why are we passing null in update.bind(...)?
//Is null here equivalent to 'this'?

<TextBox label='First Name' update={this.update.bind(null,'firstName')}></TextBox>
...

Second

Update method expects a key and a value (method definition below)

...
    update: function(key, value) {
            var newState = {};
            newState[key] = value;
            this.setState(newState);

            //this.setState({[k]:v});
        },
...

However, when it is called with a single parameter, correct key is updated with the right value.

//Aren't we supposed to pass two parameters?  
this.props.update(this.refs.newText.value);
like image 606
Bala Avatar asked Oct 24 '25 04:10

Bala


1 Answers

this.update.bind(null,'firstName') that code means - set for this.update this to null, and set first argument as a 'firstName', then when you will call this reference to function - first argument will be 'firstName' and second you can set by yourself., we can simplify code from your example like this

var fn = function (key, value) {
  console.log(key);
  console.log(value);
};

var f = fn.bind(null, 'x');

f('y');
like image 131
Oleksandr T. Avatar answered Oct 25 '25 18:10

Oleksandr T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!