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
什麼是'myVal'? –
要'onClick'你必須傳遞函數的引用而不是調用它。第二個例子是正確的例子,因爲你通過引用函數。您可以使用'.bind'而不是箭頭函數'onClick = {this.myFunc.bind(this,myVal)}' –
@PatrickRoberts將其作爲函數參數的佔位符彈出,並假定它是一個字符串。 – Ilja