显示和隐藏儿童菜单项

时间:2021-04-28 15:21:21

标签: reactjs

我有一个移动菜单,我想在其中显示子项。我创建了一个组件,用于标识菜单中哪些项目有子项。

import React from 'react'
import { BiRightArrow } from 'react-icons/bi'

const OverlayMenuChild = () => {
  return (
    <div style={{ display: 'inline-block' }}>
      <BiRightArrow
        style={{
          verticalAlign: 'bottom',
          marginLeft: '4px'
        }}
      />
    </div>
  )
}

export default OverlayMenuChild

我测试过了,所有有孩子的物品都会收到这个箭头

enter image description here

所以我创建了一个 useState 来处理有孩子的项目。

如果将状态设置为 true,则发生:

 const [childExpand, setChildExpand] = useState(true)

  const handleExpand = () => {
    setChildExpand(prev => !prev)
  }

enter image description here

显示儿童

我正在尝试但不起作用的事情:

 const [childExpand, setChildExpand] = useState(false)

  const handleExpand = () => {
    setChildExpand(prev => !prev)
  }

 <ul className="overlayMenu">
          {
            // father items
            wpMenu.menuItems.nodes.map(item =>
              !item.parentId ? (
                <li key={item.id}>
                  <Link to={item.url} activeClassName="nav-active">
                    {item.label}
                    {
                      // item with child
                      item.childItems.nodes.length !== 0 && (
                        <OverlayMenuChild onClick={handleExpand} />
                      )
                    }
                  </Link>
                  {
                    // children items
                    item.childItems.nodes.length !== 0 && childExpand ? (
                      <ul>
                        {item.childItems.nodes.map(chidItem => (
                          <li key={chidItem.id}>
                            <Link
                              to={chidItem.url}
                              activeClassName="nav-active"
                            >
                              {chidItem.label}
                            </Link>
                          </li>
                        ))}
                      </ul>
                    ) : null
                  }
                </li>
              ) : null
            )
          }
        </ul>

我尝试使用样式组件的道具,但没有得到任何结果。

li {
        display: ${props => (props.childExpand ? 'none' : 'block')};
        margin: 0 0 20px 0;
      }

我也尝试在链接上阻止Defaulf(),但也没有用。

0 个答案:

没有答案