What does the following code output

 const MainApp = () => {
  const parentRef = useRef();
  const childRef = useRef();
  const parentClickFun = useCallback(() => {
    console.log('react parent');
  }, []);
  const childClickFun = useCallback(() => {
    console.log('react child');
  }, []);
  useEffect(() => {
    document.addEventListener('click', () => {
      console.log('document');
    });
    parentRef.current?.addEventListener('click', () => {
      console.log('dom parent');
    });
    childRef.current?.addEventListener('click', () => {
      console.log('dom child');
    });
  }, []);
  return (
    <div ref={parentRef} onClick={parentClickFun}>
      <div ref={childRef} onClick={childClickFun}>
        事件执行顺序
      </div>
    </div>
  );
};

Results of the:

  • dom child
  • dom parent
  • react child
  • react parent
  • document

    code analysis

It mainly examines the difference between React synthetic events and JS native events, and their execution order. Analyzed before React16.x version. React16.x will be changed later.
Analyze the above code: it can be divided into two parts, the JS native event part and the React synthetic event part.

  • In useEffect, the event binding is done directly through addEventListener. If addEventListener does not specify the second parameter, the default is to execute in the bubbling phase. So the execution order in useEffect is dom child, dom parent, document
  • Let's look at parentClickFun, childClickFun These two functions are bound by React events. React uses the event delegation mechanism to uniformly monitor DOM events on the document, and then distribute the events to specific component instances according to the triggered target. React implements a bubbling mechanism by itself. So the execution order of this part is: react child, react parent

Finally, let's understand the entire execution order.

  • All events in react are mounted on the document
  • The react event will not be processed until the real dom triggers bubbling to the document
  • So JS native events will be executed first
  • Then execute React's synthetic events
  • Finally execute the event that is actually mounted on the document

More can be found in the articles mentioned below

refer to


IOneStar
3.1k 声望1.9k 粉丝