你需要设置
this的方法的情况下,例如,如果你需要传递函数引用到事件处理程序,但你并不需要一套
this针对每一个方法,
class Counter extends React.Component { constructor() { super(); this.tick = this.tick.bind(this); } tick() { // this refers to Counter } fn() { // this refers to Counter } withoutBind() { // this will be undefined or window it depends if you use "strict mode" or not } render() { this.fn(); // this inside this method refers to Counter // but if you will do like this const fn = this.fn; fn(); // this will refer to global scope return <div> <button onClick={this.tick}>1</button> <button onClick={this.withoutBind}>2</button> </div>; }}
Example
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)