React onClick更像是JavaScript addEventListener而不是标准JavaScript onclick属性吗? [英] Is React onClick more like a JavaScript addEventListener than like a standard JavaScript onclick attribute?
问题描述
在React中,最好将onClick设置为一个eventListener,而不是将其视为标准的JavaScript onclick属性?
例如,考虑以下两个代码段,第一个在标准JavaScript中,第二个在React中:
< button onclick =" activateLasers()">激活激光</button>< button onClick = {activateLasers}>激活激光</button>
在最上面的示例中,onclick与一个明确的CALL TO ActivateLasers函数相关联.但是,在React示例中,onClick仅与activateLasers函数相关联(语法并未明确调用该函数,即使在后台它确实调用了该函数).从这个意义上说,尽管它的名字叫React的onClick更像是这种常规的JavaScript代码:
.addEventListener("click",activateLasers)
这是错误的思考方式吗?
几乎是这样的:
//由React实现的mapEventToComponentdocument.getElementById("root").addEventListener("click",mapEventToComponent,...);
在React中,事件处理程序(例如 onClick
处理程序)是
- 打开开发工具
- 触发事件以查看其是否正常运行.
- 转到事件监听器标签.
- 检查所有事件都附加到哪个元素上.
- 从
#root
元素中删除click
侦听器.
In React is it better to think of onClick as setting an eventListener rather than as a standard JavaScript onclick attribute?
For example, consider these two code snippets, the first in standard JavaScript, the second in React:
<button onclick="activateLasers()">
Activate Lasers
</button>
<button onClick={activateLasers}>
Activate Lasers
</button>
In the top example, onclick is associated with an express CALL TO the activateLasers function. However, in the React example, onClick is simply associated with the activateLasers function (the syntax is not expressly calling the function, even though behind the scenes it does call it). In this sense, in spite of its name React's onClick is more like this conventional JavaScript code:
.addEventListener("click", activateLasers)
Or is this the wrong way to think about it?
Almost, it looks like this:
// mapEventToComponent implemented by React
document.getElementById("root").addEventListener("click", mapEventToComponent,...);
In React, event handlers (like onClick
handler) are SyntheticEvent
instances.
It helps achieve high performance by using event delegation. React attaches a single event listener to root
of the document (and not to nodes themselves), when an event called, React maps it to the component.
Check it yourself!
const Component = () => {
return <button onClick={() => console.log("hello")}>Click</button>;
};
- Open dev tools
- Fire the event to see if it's working.
- Go to Event Listeners tab.
- Check to which element all events attached.
- Remove the
click
listeners from#root
element.
这篇关于React onClick更像是JavaScript addEventListener而不是标准JavaScript onclick属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!