最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Understanding this.method.bind(null,...) in ReactJS? - Stack Overflow

programmeradmin2浏览0评论

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);

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);
Share Improve this question edited Mar 29, 2016 at 14:32 Oleksandr T. 77.5k17 gold badges176 silver badges145 bronze badges asked Mar 29, 2016 at 14:18 BalaBala 11.3k19 gold badges74 silver badges131 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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');

'Bind' is an example of how to implement the "currying" pattern in javascript. In this case it wraps the update method so that whenever update is called, this is null and 'firstName' will be the first argument (key in this case).

Unless i'm missing something, the value of 'this' when the update method is invoked will be null, unless you replace null in the bind() with bind(this, 'firstName')

发布评论

评论列表(0)

  1. 暂无评论