Javascript在使用两个参数时绑定了一个奇怪的错误



考虑以下示例

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/(转到开发人员工具中的控制台选项卡查看输出(

这里的问题是,如果只绑定一个参数,那么第二个参数就是点击事件

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

这不是一个bug。

考虑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
};

相关内容

最新更新