var foo =
x: 3
}
var bar = function () {
console.log(this.x);
}
bar(); // undefined
var boundFunc = bar.bind(foo);
boundFunc(); // 3
We create a new function that, when executed, is this
set to foo
- not the global scope, as in the example we callbar();
Pass parameters to event handlers
Usually we pass extra parameters to event handlers. For example, if id
it is the id of the row you want to delete, you can pass arguments to the event handler in either of the following ways:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
The above two methods are equivalent, passing parameters for the event handler function through arrow functions and respectively.Function.prototype.bind
上面两个例子中,参数
e
作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind
的方式,事件对象以及更多的参数将会被隐式的进行传递。
It is worth noting that when parameters are passed bind
to the listener function by means, the listener function defined in the class component, the event object e
should be arranged after the passed parameters, for example:
class Popper extends React.Component{
constructor(){
super();
this.state = {name:'Hello world!'};
}
preventPop(name, e){ //事件对象e要放在最后
e.preventDefault();
alert(name);
}
render(){
return (
<div>
<p>hello</p>
{/* Pass params via bind() method. */}
<a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
</div>
);
}
}
conditional rendering
In React, you can create different components to encapsulate the various behaviors you need. Then you can also render only part of it based on the state of the application. ( Because the attributes of an object can be assigned to another object, the current object where the attribute is located is mutable, that is,this
the pointer is mutable,
(这里已经清楚了说明了,箭头函数没有自己的 this
绑定。箭头函数中使用的 this
,其实是直接包含它的那个函数或函数表达式中的 this
。比如const obj = {
test() {
const arrow = () => {
// 这里的 this 是 test() 中的 this,
// 由 test() 的调用方式决定
console.log(this === obj);
};
arrow();
},
getArrow() {
return () => {
// 这里的 this 是 getArrow() 中的 this,
// 由 getArrow() 的调用方式决定
console.log(this === obj);
};
}
};
obj.test(); // true
const arrow = obj.getArrow();
arrow(); // true)