![](/img/trans.png)
[英]when communicate between component in react or vuejs, what's the different between using callback and event
[英]What is “this” referring to when binding event callback function in React component with “null” argument?
在此React教程中, React Presentational Component內部的按鈕單擊事件回調函數顯式綁定為null
:
<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button>
但是,在回調函數內部, this
關鍵字用於訪問React容器組件的狀態:
toggleActive: function(userId) {
...
var newState = Object.assign({}, this.state)
...
}
我不明白為什么這個例子工程時, this
應該等於null
,或者在非嚴格模式,全球的window
對象。 誰能告訴我為什么該示例仍然有效?
相應的Codepen可以在這里找到。
<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button>
在這里,您有約束力的方法
null
,而不是instance.Hence您不能訪問this
方法中,因此this
將無法正常工作。
我之前錯了,不明白這個問題,看下面的代碼:-
function a(){
this.x = 5;
this.y = function(){
console.log(this.x)
}
}
var x = 20;
var c = new a();
var d = c.y.bind(null);
d(); // prints 20 and not null or undefined
當將null作為綁定函數中的上下文傳遞時,該函數將保留其原始上下文,即此處的全局范圍(定義了函數d的上下文)。但是,如果在綁定函數中傳遞了某些上下文,則該函數將打印出“ x”該上下文的屬性。
同樣,當您傳入null時
<button onClick={_this.props.toggleActive.bind(null, user.id)}>Toggle Active</button>
觸發時,toggleActive函數內部的上下文是定義它的上下文,即UserListContainer的上下文。因此,它能夠訪問其狀態
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.