Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

reactjs - Is React onClick more like a JavaScript addEventListener than like a standard JavaScript onclick attribute?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Edit Synthetic Event

  1. Open dev tools
  2. Fire the event to see if it's working.
  3. Go to Event Listeners tab.
  4. Check to which element all events attached.
  5. Remove the click listeners from #root element.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...