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
486 views
in Technique[技术] by (71.8m points)

reactjs - Setting state with delay via onMouseEnter in React component

I have a menu that consists of a series of Material UI's ListItems. When the mouse enters a given item, I use one of the props to lift up state to the parent component, which is in charge to determine which submenu it needs to show. Here are the relevant lines:

  • onMouseEnter in each list item:
onMouseEnter={event => openDropDown(event, menuItem, subMenuItem)}
  • openDropDown calls setSubMenuItem to lift up the state:
  const openDropDown = (event, menuItem, subMenuItem) => {
    if (subMenuItem.subMenu) {
      setSubMenuItem({ ...subMenuItem, parent: menuItem });
      setAnchorEl(event.target.getBoundingClientRect());
    } else {
      closeDropDown();
    }
  };

However, the state transition is slower than the mouse movement. This causes the state to "get stuck" in the first item on the path to the destination. Thus, the submenu for items 2 and 6 are shown in scenarios A and B, respectively (instead of 4 and 3 as expected):

enter image description here

Any ideas to ensure that setting the state will be in sync with the mouse movement will be more than welcome. I tried calling openDropDown inside of a setTimeout but it results in each submenu popping up as I move from one item to the next.

question from:https://stackoverflow.com/questions/66048259/setting-state-with-delay-via-onmouseenter-in-react-component

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

1 Answer

0 votes
by (71.8m points)

I ended up delaying the state transition as suggested in this thread, and worked like a charm.


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

...