[英]React useState boolean issue (functional component)
I am having trouble with useState
and state change in a React Functional Component.我在使用 React 功能组件中的
useState
和 state 更改时遇到问题。 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.我正在使用一个名为
Menu
的导入 package,它采用一个名为“ isOpen ”的道具 - 当设置为 true 时,将显示菜单(类似于模式)。
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.当我单击菜单模式中的“关闭菜单”按钮时,menuOpen 的
menuOpen
变为 false - 但是, isOpen 道具不会从 true 切换到 false - 因此菜单不会关闭。 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. 'pcln-menu' package 绝对是一个问题,因为它的开发人员在设计组件的 state 时不使用单一事实来源原则。
You should pass menu content as renderContent
property to obtain handleClose
callback.您应该将菜单内容作为
renderContent
属性传递以获取handleClose
回调。 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>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.