var foo = {
x: 3
}
var bar = function(){
console.log(this.x);
}
bar(); // undefined
var boundFunc = bar.bind(foo);
boundFunc(); // 3
我们创建了一个新的函数,在执行时,它的this
设置为foo
- 而不是全局范围,就像我们调用的例子bar();
向事件处理程序传递参数
通常我们会为事件处理程序传递额外的参数。例如,若是 id
是你要删除那一行的 id,以下两种方式都可以向事件处理程序传递参数:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
上述两种方式是等价的,分别通过 arrow functions 和 Function.prototype.bind
来为事件处理函数传递参数
上面两个例子中,参数
e
作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind
的方式,事件对象以及更多的参数将会被隐式的进行传递。
值得注意的是,通过 bind
方式向监听函数传参,在类组件中定义的监听函数,事件对象 e
要排在所传递参数的后面,例如:
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>
);
}
}
条件渲染
在 React 中,你可以创建不同的组件来封装各种你需要的行为。然后还可以根据应用的状态变化只渲染其中的一部分。(由于对象的属性可以赋给另一个对象,所以属性所在的当前对象是可变的,即this
的指向是可变的,
(这里已经清楚了说明了,箭头函数没有自己的 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)