如何将props传递给material-ui中传递给MenuItem的组件

时间:2019-02-14 09:55:16

标签: reactjs material-ui

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

      <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组件。

2 个答案:

答案 0 :(得分:1)

如果需要的话,只需在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>

答案 1 :(得分:0)

经过研究,我在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}
          />
        ))}