Fail creating a SubMenu in a component with antd

回眸只為那壹抹淺笑 提交于 2019-12-14 03:55:14

问题


I'm using antd: ^3.5.4

I have a menu that contains items for user management. When not logged the menu has a menuItem with a Link to Login page When logged in, the menu has a SubMenu with several links including Log out

I just make a simple test on my user connected to display the link or the submenu. I works well when all in the same file

    <Menu mode="horizontal">
      <Menu.Item key="home">
        <Link to={RoutesNames.HOMEPAGE}>Home</Link>
      </Menu.Item>
      {this.props.currentUserIsSignedIn ? ( 
      <SubMenu key="usermenu" title={<Avatar>A</Avatar>}> 
        <Menu.Item key="info">{this.props.currentUserEmail}</Menu.Item> 
        <Menu.Item key="logout"> 
          <Link onClick={this.props.signOutUser}>Log out</Link> 
        </Menu.Item> 
      </SubMenu> 
      ) : ( 
      <Menu.Item key="login"> 
        <Link to={RoutesNames.LOGIN}>Signin / Register</Link> 
      </Menu.Item> 
      )} 
    </Menu>

The problems begin when I try to create a Component UserMenu that handle this logic. What I want to have at the end is

    <Menu mode="horizontal">
      <Menu.Item key="home">
        <Link to={RoutesNames.HOMEPAGE}>Home</Link>
      </Menu.Item>
      <UserMenu user={this.props.currentUser}/>
    </Menu>

I create my sub component UserMenu.

First I have this error:

    Uncaught TypeError: Cannot read property 'isRootMenu' of undefined
at ProxyComponent.render (SubMenu.js:274)

So I updated my UserMenu component to define parentMenu

   <SubMenu parentMenu={this.props.menu}

and set the parent as parentMenu in my header file

   <Menu
     mode="horizontal"
     ref={el => this.menu = el}
   >
     <UserMenu menu={this.menu} user={this.props.currentUser} />
   </Menu>

With this menu props the subMenu is showing but I still got an error when mouseover and mouseout the submenu

    Uncaught TypeError: onItemHover is not a function
at onTitleMouseEnter (SubMenu.js:454)

For this one I have absolutely no idea what to do.

Thanks for your help


回答1:


Menu passes additional props down to it's children. You need to make sure those props are passed down from your UserMenu component to the SubMenu component that you render. You can do this with an object spread operator. Example:

const UserMenu = (props) => {
     const {username, customProp, ...other} = props;

     return <SubMenu {...other}>
          This is my {customProp} for {username}
     </SubMenu>
}


来源:https://stackoverflow.com/questions/50573609/fail-creating-a-submenu-in-a-component-with-antd

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!