2017-04-20 39 views
-1

我很困惑,应该在ReactJS中绑定胖箭头函数吗?我很困惑,应该在ReactJS中绑定胖箭头函数吗?

正常功能,不无约束力的正常工作,但我不知道胖箭头函数应该绑定或者不

+2

的可能的复制[?如何使用ES6类方法箭头(http://stackoverflow.com/questions/31362292/how-to-use-es6 -arrow-in-class-methods) –

+0

'myFunc.bind(this)'与'()=> this.myFunc()'相同。 – Sulthan

回答

1

不,你不需要绑定this为箭头的功能。它们与封闭上下文具有相同的this值。

this.myValue = 5; 

const myFunc =() => { 
    this.myValue = 10; 
} 

myFunc(); 

console.log(this.myValue); // 10 

有关更多详细信息,请参见here

+1

谢谢你清除我的概念 –

1

如果您的绑定功能需要this(这似乎是强制性的),您实际上需要正确绑定this。最好的方式(由airbnb eslinter推荐)是胖箭头功能。

作为为例,让我们假设我有这个组件:

class MyComponent extends React.Component { 

    toBeRunOnSpanClick() { 
    this.props.clickHandler(); 
    } 

    render() {return <span onclick={/* What should you use here*/}></span>} 
} 

这是行不通的:

class MyComponent extends React.Component { 

    toBeRunOnSpanClick() { 
    this.props.clickHandler(); 
    } 

    render() {return <span onclick={this.toBeRunOnSpanClick}></span>} 
} 

在toBeRunOnSpanClick功能this不会比你的类相同。这是JavaScript的工作方式。

的好办法是:

class MyComponent extends React.Component { 

    toBeRunOnSpanClick() { 
    this.props.clickHandler(); 
    } 
    // this.toBeRunOnSpanClick.bind(this) will work too but it is way less comprehensive 
    render() {return <span onclick={() => {this.toBeRunOnSpanClick()}}></span>} 
}