如何open/close单下拉菜单

How to open/close single dropdown menu

我已经创建了映射下拉菜单,但不知道如何 open/close 选择一个 我已经有了这样的想法

{navItems.map(({ id, icon, text}) => (
                    <Dropdown>
                        <DropdownButton id={id} onClick={() => handleIsOpen(id)}>{text}{icon ? <img src={icon} alt="arrow-down" /> : null}</DropdownButton>
                        <DropdownContent isOpen={isOpen}>
                            <DropdownLink href="#">Link 1</DropdownLink>
                            <DropdownLink href="#">Link 2</DropdownLink>
                            <DropdownLink href="#">Link 3</DropdownLink>
                        </DropdownContent>
                    </Dropdown>
                ))}

handleIsOpen 函数

const [isOpen, setIsOpen] = useState({
    1: false,
    2: false,
});

const handleIsOpen = (id) => {
    if (id === 1 || id === 2) {
        setIsOpen({
            [id]: !isOpen[id],
        })
    } else {
        setIsOpen({
            ...isOpen,
            3: false,
            4: false,
        })
    }
}

实际上当我点击按钮时它并没有改变它的样式

export const DropdownContent = styled.div`
   display: ${({isOpen}) => isOpen ? 'none' : 'block'};
   position: absolute;
   background-color: white;
   min-width: 128px;
   box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
   z-index: 1;
`;

问题是您只是将 isOpen 用作布尔值。对象总是真实的,所以你应该检查对象的实际条目。

{navItems.map(({ id, icon, text}) => (
                    <Dropdown>
                        <DropdownButton id={id} onClick={() => handleIsOpen(id)}>{text}{icon ? <img src={icon} alt="arrow-down" /> : null}</DropdownButton>
                        <DropdownContent isOpen={!!isOpen[id]}>
                            <DropdownLink href="#">Link 1</DropdownLink>
                            <DropdownLink href="#">Link 2</DropdownLink>
                            <DropdownLink href="#">Link 3</DropdownLink>
                        </DropdownContent>
                    </Dropdown>
                ))}