In the development of a right click operation on an object, sometimes we need to customize the encapsulation of a right click menu component, the implementation code is as follows:

(1Build a menu (hidden by default) <div id={"Menu"} className={styles.MenuContainer}>
                <ul  onClick={(e)= > getOption(e)} >
                  <li>To view</li>
                  <li>The editor</li>
                  <li>public</li>
                  <li>Set the password</li>
                  <li>download</li>
                  <li>delete</li>
                </ul>
  </div>
 (2) right click div to go to the event handler openNoteMenu(e);<div onContextMenu={(e)= >openNoteMenu(e)} 
     className={styles.NoteBlock}>
     <p>{item.title}</p>
 </div>
 (3) gets the scrolling distance of the scroll bar; useEffect(() = > {
      const addeventLister= window.onscroll = function() {
      let duration:any = document.documentElement.scrollTop || document.body.scrollTop;
      console.log("Monitoring distance from top",duration);
      setDuration(duration)
  } 
   addeventLister()    
  }, []);
 (4) Set the location of the menuconst openNoteMenu=(e:any) = >{
    e.preventDefault()
    console.log("Right click event",e);
    const clickX = e.clientX
    const clickY = e.clientY
    const Menu:any= document.getElementById("Menu")
    Menu.style.display="block"
    Menu.style.position="absolute"
    Menu.style.left=`${clickX}px`
    // appear pixels away from the left border of clickX;
    Menu.style.top=`${clickY+Duration}px`
    ClickY +Duration pixels on the upper edge of the distance;
 }
 (5) Click anywhere on body to close the menu;const bodyHandle=() = >{
    dispatch(changeSearchFilterStatusAC(false))
    dispatch(changePublishFilterStatusAC(false))
    const Menu:any= document.getElementById("Menu")
    Menu.style.display="none"
  }
 (6) Click options to close the menu;const getOption=(e:any) = >{
  e.stopPropagation();
  // Because the body event is set, there is a bubbling prevention;
  console.log(e.target.innerText);
  const Menu:any= document.getElementById("Menu")
  Menu.style.display="none"
 }
Copy the code