2017-02-23 74 views
1

我讀的思維在https://facebook.github.io/react/docs/thinking-in-react.html使用在反向數據流綁定(本)發生反應

陣營文檔中的文件https://facebook.github.io/react/docs/thinking-in-react.html#step-5-add-inverse-data-flow的最後一部分,我無法理解的使用綁定的(這)以及它是如何工作的。具體來說,我想明白了:

爲什麼我們需要在搜索欄組件這兩條線:

this.handleFilterTextInputChange = this.handleFilterTextInputChange.bind(this); 
this.handleInStockInputChange = this.handleInStockInputChange.bind(this); 

而下面的兩行FilterableProductTable組件:

this.handleFilterTextInput = this.handleFilterTextInput.bind(this); 
this.handleInStockInput = this.handleInStockInput.bind(this); 

會發生什麼如果我們不要這些約束?

我已經閱讀了關於JavaScript綁定函數的文檔以及我在Google上發現的反向數據流的一些示例,但仍無法獲得我的頭。

希望有人能解構數據流,並在每種情況下引用什麼this

+0

閱讀此項。 https://medium.com/@rjun07a/binding-callbacks-in-react-components-9133c0b396c6#.4mthme884 – Nick

+0

更一般地說:[使用JavaScript'綁定'方法](http://stackoverflow.com/q /218196分之2236747) –

回答

0

bind調用返回一個新函數,該函數將此(上下文)設置爲給定值來調用綁定函數。如果你進一步關注這個例子,你會發現這兩個函數是作爲回調方法/事件處理程序給予子組件的。

如果沒有綁定,子組件必須確保使用正確的上下文(它們的父級)調用回調。這會不必要地將這些組件連接起來,給開發者帶來很大的負擔,不要忘記這一點。

如果父組件將回調綁定到自身,它可以確保子組件(應該使用回調的人)不必知道這一點,只需調用回調即可。

0

在函數對象上調用bind()允許從任何上下文中調用該函數對象,而不更改其this。因此,例如,你可以這樣做:

// Inside the SearchBar component 
this.handleFilterTextInputChange = this.handleFilterTextInputChange.bind(this); 
this.handleInStockInputChange = this.handleInStockInputChange.bind(this); 

// Elsewhere 
someOtherObj.doTheThing = this.handleFilterTextInputChange; 

// And inside someOtherObj 
someClassMethod : function() { 
    this.doTheThing(); 
} 

在這種調用doTheThing(),如果你沒有所謂的綁定(本)以上,則handleFilterTextInputChange裏面this任何引用將指向someOtherObj。儘管您調用bind,即使您已將該函數傳遞到完全不同的上下文中,this仍將指向SearchBar組件。

簡而言之,bind()允許您確保無論什麼情況下調用函數,無論您傳遞給bind()什麼情況,都將是this