ReactJs需要一个破坏布局的包装div

时间:2016-07-07 09:11:23

标签: javascript reactjs

我有以下React代码:

render() {
    return (
      <NavItem dropdown toggleOnHover className='collapse-left'>

        <DropdownButton nav>
          <Icon bundle='fontello' glyph='bullhorn' />
          {this.getBadge()}
        </DropdownButton>
        <Menu alignRight ref='bullhorn-menu' id='notifications-menu' className='double-width' alwaysInactive>
          <MenuItem header>
            <Entity entity='Notifications' />
          </MenuItem>

          {this.state.notifications.map((item, index) => {
            return (
              <Notification notification={item} key={index} />
            )
          })}

          <MenuItem noHover>
            <Grid collapse style={{marginBottom: -10}}>
              <Row>
                <Col xs={12} collapseLeft collapseRight>
                  <Button block className='notification-footer-btn left-btn'>MARK ALL READ</Button>
                </Col>
              </Row>
            </Grid>
          </MenuItem>
        </Menu>
      </NavItem>
    )
  }

上面的代码不起作用,因为它抛出:

react-with-addons.js:9729 Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

但是,当我用div包围map()语句时,它可以工作,但是会破坏布局。

Notification组件只返回如下内容:

<MenuItem href='/'>
        <Grid>
          <Row>
            <Col xs={2} className='avatar-container' collapseRight>
              <div><img src='/imgs/avatars/avatar22.png' width='40' height='40' alt='sarah_patchett' /></div>
              <div className='text-center'>
                <BLabel bsStyle='info'>NEW</BLabel>
              </div>
            </Col>
            <Col xs={10} className='notification-container' collapseLeft collapseRight>
              <div className='time'>
                <strong className='fg-darkgray50'><Icon bundle='fontello' glyph='chat-5'/><em><Entity entity='notificationsTimeFirst' /></em></strong>
              </div>
              <div className='message-header'>
                <strong className='fg-darkgreen45'>Sarah Patchett sent you a private message</strong>
              </div>
              <div className='message-details fg-text'>
                <span>{"Hey Anna! Sorry for delayed response. I've just finished reading the mail you sent couple of days ago..."}</span>
              </div>
            </Col>
          </Row>
        </Grid>
      </MenuItem>

有人可以告诉我如何循环我的数组并渲染Notification组件,而不包含周围的div?

1 个答案:

答案 0 :(得分:3)

Currently it is not possible to return multiple components like that,所以你需要把它们包装好。

为什么不直接更改容器的样式以使其不会破坏布局?

例如:

<div style={{ display: "inline" }}>
    {this.state.notifications.map((item, index) => {
        return (
            <Notification notification={item} key={index} />
        )
    })}
</div>

或者,你可以这样做:

let menuItems = [
    <MenuItem header key="header">
        <Entity entity='Notifications' />
    </MenuItem>
].concat(notifications);

return <Menu>
    { menuItems }
</Menu>;

现在菜单的内容是一个数组,因此每个项目都需要一个键。