2017-01-16 80 views

回答

3

<MyButton onPress={() => {doSomething(data)} }>

該代碼塊使用ES6 Arrow功能;這是另一種在javascript中聲明函數的方法。另外,箭頭函數中的this的範圍取決於創建函數的位置,與正常的作用域規則this相反,默認取決於函數的作用域如何稱爲

<MyButton onPress={ this.doSomething.bind(this) }>

這種說法使得以doSomething方法的調用。但由於事件註冊是在不同的元素上完成的,因此doSomething的範圍是不同的,並且在javascript中使用bind方法強制綁定。

另外,在第二種方法中,您沒有傳遞數據參數,您可以使用第二個參數傳遞數據參數,如下所示。

<MyButton onPress={ this.doSomething.bind(this, data)} }>

3
<MyButton onPress={() => {doSomething(data)} }> 

在呼喚一個新的匿名功能onPress,這將運行doSomething

<MyButton onPress={ this.doSomething.bind(this) }> 

是打電話來命名函數的引用,你已經在你的類中定義。只有當您使用類函數(我的意思是,非ES6箭頭函數)時,才需要綁定到此。

const doSomething =() => { ... } 

將不需要0​​,因爲箭頭的功能結合在lexical scope

您應該明確地閱讀What is the best and most efficient way to bind callbacks in ReactJS? In the constructor or in the render method or as a property initializer?