在組件中,我看到了回調的不同方式。是什麼區別:React原生組件回調函數
<MyButton onPress={() => {doSomething(data)} }>
和
<MyButton onPress={ this.doSomething.bind(this) }>
在組件中,我看到了回調的不同方式。是什麼區別:React原生組件回調函數
<MyButton onPress={() => {doSomething(data)} }>
和
<MyButton onPress={ this.doSomething.bind(this) }>
<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)} }>
<MyButton onPress={() => {doSomething(data)} }>
在呼喚一個新的匿名功能onPress
,這將運行doSomething
。
<MyButton onPress={ this.doSomething.bind(this) }>
是打電話來命名函數的引用,你已經在你的類中定義。只有當您使用類函數(我的意思是,非ES6箭頭函數)時,才需要綁定到此。
const doSomething =() => { ... }
將不需要0,因爲箭頭的功能結合在lexical scope。