考慮以下示例
export default function App() {
const newFunction = (valueOne, valueTwo) => {
console.log('valueOne:', valueOne, 'valueTwo:', valueTwo)
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={newFunction.bind(this, 1)}> Bind (single param) </button>
<br />
<button onClick={newFunction.bind(this, 1, 2)}>Bind (two params) </button>
</div>
);
}
在這里,這個 React 應用程式在每次單擊按鈕元素時都會呼叫onClick事件newFunction。傳遞引數.bind()已被使用。
每當為 傳遞兩個引數時newFunction,輸出都會按預期在控制臺中列印。例如:newFunction.bind(this, 1, 2)輸出到 =>valueOne: 1 valueTwo: 2
問題:然而,在傳遞單個引數時newFunction.bind(this, 1),輸出如下所示,
valueOne: 1
valueTwo: SyntheticBaseEvent {_reactName: "onClick", _targetInst: null, type: "click", nativeEvent: PointerEvent, target: HTMLButtonElement…}
_reactName: "onClick"
_targetInst: null
type: "click"
nativeEvent: PointerEvent
target:
<button> Bind (single param) </button>
currentTarget: null
eventPhase: 3
bubbles: true
cancelable: true
timeStamp: 12358.5
defaultPrevented: false
isTrusted: true
view: Window
detail: 1
screenX: 2017
screenY: 328
clientX: 571
clientY: 97
pageX: 571
pageY: 97
ctrlKey: false
shiftKey: false
altKey: false
metaKey: false
getModifierState: ? modifierStateGetter() {}
button: 0
buttons: 0
relatedTarget: null
movementX: 0
movementY: 0
isDefaultPrevented: ? functionThatReturnsFalse() {}
isPropagationStopped: ? functionThatReturnsFalse() {}
preventDefault: ? preventDefault() {}
stopPropagation: ? stopPropagation() {}
persist: ? persist() {}
isPersistent: ? functionThatReturnsTrue() {}
<constructor>: "SyntheticBaseEvent"
的預期輸出newFunction.bind(this, 1)應該是valueOne: 1 valueTwo: undefined因為第二個引數不存在。相反,它的行為方式不同。
Codesandbox URL:https ://v12ek.csb.app/ (轉到開發人員工具中的控制臺選項卡以查看輸出)
uj5u.com熱心網友回復:
這里的問題是,如果你只系結一個引數,第二個是點擊事件
const newFunction = (valueOne, valueTwo) => {
console.log('valueOne:', valueOne, 'valueTwo:', valueTwo)
};
const fakeEvent = {event: 'click'}
newFunction.bind(this, 1, 2)(fakeEvent) //this works
newFunction.bind(this, 1)(fakeEvent)
newFunction.bind(this, 1, undefined)(fakeEvent) //this works
uj5u.com熱心網友回復:
這不是一個錯誤。
考慮到newFunction.bind(this, 1, 2),
使用 bind ( 1, 2)傳遞的引數和呼叫回傳函式時傳遞的引數(newFunction.bind(this, 1, 2)回傳一個函式,該函式在單擊按鈕時使用 'click' 事件呼叫)組合并傳遞給newFunction.
你沒有看到事件,newFunction.bind(this, 1, 2)因為newFunction只需要兩個引數。如果修改為采用另一個,您也可以在這種情況下看到該事件。
const newFunction = (valueOne, valueTwo, valueThree) => {
console.log(valueOne, valueTwo, valueThree); // valueThree will be the event
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/394862.html
