我正在通过示例学习ReactJS(Mastering React)。在重现例子时,我对其中的几句话一无所知,希望能得到一些帮助。
Fiddle:合成组件
第一个
...
//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>
...
第二个
更新方法需要一个键和一个值(方法定义如下)
...
update: function(key, value) {
var newState = {};
newState[key] = value;
this.setState(newState);
//this.setState({[k]:v});
},
...
但是,当使用单个参数调用它时,正确的键将使用正确的值更新。
//Aren't we supposed to pass two parameters?
this.props.update(this.refs.newText.value);
this.update.bind(null,'firstName')
,代码的意思是-为this.update
设置this
到null
,并将第一个参数设置为'firstName'
,然后当您将此引用调用到函数时,第一个参数将为'firstName'
,第二个参数可以自己设置。,我们可以简化你的例子中的代码,比如这个
var fn = function (key, value) {
console.log(key);
console.log(value);
};
var f = fn.bind(null, 'x');
f('y');
‘Bind’是如何在javascript中实现"currying"模式的一个示例。在这种情况下,它包装了update方法,因此无论何时调用update,它都为null,并且"firstName"将是第一个参数(在这种情况中为键)。
除非我遗漏了什么,否则调用更新方法时"this"的值将为null,除非您将bind()中的null替换为bind(this,"firstName")