React modal method to implement closing events: 1. Listen to the target of the browser onclick event; 2. Determine the click through the "if (e.target != messageRef.current) {setMessageCode(false);}" statement Event, if it is not a modal box, just execute the closing event.
#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.
How to implement closing event in react modal?
reactClick somewhere else to close the Modal box
Principle: Very simple, it is to listen to the target of the browser onclick event, determine the click event, and execute the closing event if it is not a modal box.
Server-side rendering cannot get the window object in useEffect
useLayoutEffect(() => { window.addEventListener("click", (e) => { if (e.target != messageRef.current) { setMessageCode(false); } }); }, []);```
const messageRef = useRef(null);
```
The function signature of useLayoutEffect is the same as useEffect, but it will be synchronized after all DOM changes Call effect. You can use this to read the DOM layout and trigger re-rendering synchronously. Before the browser performs drawing, the update plan inside useLayoutEffect will be refreshed synchronously.
Recommended learning: "react video tutorial"
The above is the detailed content of How to implement closing event in react modal. For more information, please follow other related articles on the PHP Chinese website!