代码之家  ›  专栏  ›  技术社区  ›  ManavM

如何将道具传递给物料界面中传递给menuitem的组件

  •  0
  • ManavM  · 技术社区  · 6 年前

    我有以下代码来呈现通知菜单

          <Menu
            anchorEl={notificationAnchorEl}
            anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
            transformOrigin={{ vertical: 'top', horizontal: 'right' }}
            open={isNotificationMenuOpen}
            onClose={this.handleNotificationMenuClose}
          >
            {notifications.map(notification => (
              <MenuItem
                key={notification.id}
                component={NotificationItem}
                onClick={this.handleNotificationMenuClose}
              />
            ))}
          </Menu>
    

    我不明白的是我怎么把道具传给 NotificationItem 组件使用 notification 我有东西。

    0 回复  |  直到 6 年前
        1
  •  1
  •   darksmurf    6 年前

    只是渲染一个 NotificationItem 里面 MenuItem 如果那是你想要的。

    另外,记得要通过一个独特的 key 支持从数组映射的每个元素。

    <Menu
        anchorEl={notificationAnchorEl}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        open={isNotificationMenuOpen}
        onClose={this.handleNotificationMenuClose}
    >
        {notifications.map((notification, i) => (
            <MenuItem
               key={i}
               onClick={this.handleNotificationMenuClose}
            >
                <NotificationItem someProp={notification.someProp}/>
            </MenuItem>
        ))}
    </Menu>
    
        2
  •  0
  •   ManavM    6 年前

    经过一番研究,我在 implementation of the ListItem Component .

    原来所有给listitem的附加道具都传递给了 component .

    const {
      .
      .
      .
      component: componentProp,
      ...other
    } = props;
    .
    .
    .
    const componentProps = { className, disabled, ...other };
    let Component = componentProp || 'li';
    .
    .
    .
    return (
      <ContainerComponent
        className={classNames(classes.container, ContainerClassName)}
        {...ContainerProps}
      >
        <Component {...componentProps}>{children}</Component>
        {children.pop()}
      </ContainerComponent>
    );
    

    ^来自listitem.js的相关代码

    所以下面的代码可以工作

            {notifications.map(notification => (
              <MenuItem
                component={NotificationItem}
                onClick={this.handleNotificationMenuClose}
                notification={notification}
              />
            ))}