简体   繁体   中英

React useState boolean issue (functional component)

I am having trouble with useState and state change in a React Functional Component. I am using an imported package called Menu that takes a prop called " isOpen " - when set to true the Menu (similar to a modal) is displayed.

When I click on the "Close Menu" button that is within the Menu modal, the state for menuOpen changes to false - however, the isOpen prop does not switch from true to false - and therefore the menu does not close. Or else Am I missing something here?

const MenuButton: React.FC<Props> = () => {
  const [menuOpen, setMenuOpen] = useState(false)
  const openMenu = () => {
  setMenuOpen(true)
}

const closeMenu = () => {
  setMenuOpen(false)
}

 return (
 <Menu buttonNode={<Button onClick={openMenu}>Open 
 Menu</Button>} isOpen={menuOpen}>
   <Box>
     <Text>Menu Heading</Text>
     <Button onClick={closeMenu}>Close Menu</Button>
   </Box>
 </Menu>
 )
}

It's definitely a problem with 'pcln-menu' package as it's developers don't use the single source of truth principle when designing component's state.

You should pass menu content as renderContent property to obtain handleClose callback. Try this:

const MenuButton = () => {
  const [menuOpen, setMenuOpen] = useState(false);
  const openMenu = () => {
    setMenuOpen(true);
  };

  return (
    <Menu
      buttonNode={<Button onClick={openMenu}>Open Menu</Button>}
      isOpen={menuOpen}
      renderContent={({handleClose}) => (
        <Box>
          <Text>Menu Heading</Text>
          <Button onClick={handleClose}>Close Menu</Button>
        </Box>
      )}
    ></Menu>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM