2016-05-31 27 views
1

我得到這個行爲發生的onClick真的惱火:停止的onClick功能,無需使用()上安裝執行=>函數(someVal)

如果我有:

<button onClick={ this.myFunc(myVal) }></button> 

這爲火災一旦組件坐騎被點擊按鈕的時候,所以我需要做的,爲了解決這個問題如下:

<button onClick={() => this.myFunc(myVal) }></button> 

但我相信這不是實現這一目標的正確方法是什麼?另外如果我想實際上將this.myFunc(myVal)傳遞給另一個組件,該怎麼辦?它不會工作。

+0

什麼是'myVal'? –

+2

要'onClick'你必須傳遞函數的引用而不是調用它。第二個例子是正確的例子,因爲你通過引用函數。您可以使用'.bind'而不是箭頭函數'onClick = {this.myFunc.bind(this,myVal)}' –

+0

@PatrickRoberts將其作爲函數參數的佔位符彈出,並假定它是一個字符串。 – Ilja

回答

-1

onClick屬性預計函數作爲參數。 這就是爲什麼第二設置是正確的,並且第一一個不是(除非myFunc的返回的函數)..

以下是功能:

(event) => myFunc(myVal, event)  // anonymous function, which calls myFunc IF executed 
myFunc.bind(this, myVal) // myFunc without parentheses, with parameters - including event - bound 

以下是不是一個函數

myFunc(myVal)    // == THE RESULT of the function, so == whatever myFunc returns 

在一個例子:

// myFunc is a function that calls another function 
// returns length of whatever is passed in 
myFunc(val) { 
    otherFunc() 
    return (val.length) 
} 
// here: myFunc is defined, but it has never executed: otherFunc was not called 

let myVal = [1,2] 

let callback =() => myFunc(myVal) 
// here myFunc is still NOT called, neither is otherFunc 
// callback is now defined as a (anonymous) function, which, whenever called 
// will execute the function myFunc, by passing in the value of myVal 

let a = myFunc(myVal) 
// here: myFunc WILL be called, so also otherFunc 
// at this point a == 2 (the length of the array myVal) 

let b = callback() 
// here, callback function is executed, and so also myFunc 
// at this point b == 2 
+0

'()=> myFunc(myVal)'和'myFunc。bind(this,myVal)'是不一樣的。如果需要使用'event',則只有'.bind()'變體才能正常工作。 –

+0

謝謝你指出。不知道。將更新答案。 – wintvelt

+0

考慮簽名函數myFunc(val,event){...}來理解爲什麼是這種情況。 –

0

您呼叫的功能,而做這樣的下方,這就是爲什麼你的方法被安裝

<button onClick={ this.myFunc(myVal) }></button> 

你必須只分配功能類似下面

<button onClick={ this.myFunc }></button> 

,如果你想後立即調用將變量傳遞給該方法,添加該變量以聲明並訪問它。

+0

@ctrlplusb如果你仔細閱讀,你不會。 @sundar建議將'myVal'置於狀態,以避免事件回調中的默認參數的反模式。 –

+0

@Patrick Roberts yes.if myVal更改組件視圖,您可以擁有內部狀態。 – sundar

3

當你說

<button onClick={ this.myFunc(myVal) }></button> 

你告訴陣營要從執行this.myFunc(myVal)返回值被分配到onClick處理程序。相反,你大概想給它的功能與設置爲默認的參數:

<button onClick={ this.myFunc.bind(this, myVal) }></button> 

這種結合myVal作爲第一個參數this.myFunc並確保上下文也正確綁定爲好。請記住,這會導致event參數作爲函數的第二個參數傳入。