[英]Difference between passing event handler prop as arrow function or function reference
In a class Component, I have something like this:在 class 组件中,我有这样的东西:
render() {
const { onClose } = this.props;
// later, in the return statement, inside a bunch of other nested markup:
<CloseIcon onClick={() => onClose()} className="qmCloseButton" />
<AnotherIcon onClick={() => onClose("/path1")} className="qmCloseButton" />
<AnotherIcon onClick={() => onClose("/path2")} className="qmCloseButton" />
}
The close handler prop that I pass in is:我传入的关闭处理程序道具是:
const onCloseModal = urlAfterClose => {
if (urlAfterClose) {
history.push(urlAfterClose);
} else {
setShowSuccessModal(false);
}
};
Everything works.一切正常。 However, I always like to avoid arrow functions in my markup when I can, so I try this small change:
但是,我总是喜欢尽可能避免在我的标记中使用箭头函数,所以我尝试了这个小改动:
<CloseIcon onClick={onClose} className="qmCloseButton" />
<AnotherIcon onClick={() => onClose("/path1")} className="qmCloseButton" />
<AnotherIcon onClick={() => onClose("/path2")} className="qmCloseButton" />
But for the CloseIcon
, the onClose
method gets called with a class (looks like it might be the component itself?) instead of being called with no argument.但是对于
CloseIcon
,使用 class 调用onClose
方法(看起来可能是组件本身?)而不是在没有参数的情况下调用。 It only works as an arrow function.它只能用作箭头 function。
What am I missing here?我在这里想念什么?
It's totally different syntaxes这是完全不同的语法
onClick={onClose} =/= () => onClick={()=>onClose()}
onClick={onClose}
in JavaScript this will pass all arguments available to onClose function, which second one runs without params JavaScript 中的
onClick={onClose}
这将传递所有可用于 onClose function 的 arguments,第二个运行没有参数
its same as它与
onClick={onClose} = onClick={(e)=>onClose(e)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.