Reactjs 在 Render 方法中包含 HTML 和子组件

Reactjs include HTML alongside child component in Render method

正在努力实现以下目标。在渲染我的子组件时,我需要在第 4 个和第 5 个子组件之间放置一个分隔符(<hr />)。然而,当我使用下面的代码时,所有渲染到 DOM 的都是 [Object object]null。如果我删除 hr,它会完美呈现。

<div>
    {this.props.items.map(function(c, ind) {
        var hr = ((ind == 3) ? <hr /> : null);
        return <Item id={c.id} /> + hr;
    }.bind(this))}
</div>

+ 用于字符串连接,但 <Item><hr> 是对象。 + 正在对它们调用 toString,这就是为什么你得到 [Object object]null

你可以照你说的做,先映射 4,再映射 HR,再映射最后 4。

另一种选择是使用 reduce,例如:

<div>
    {this.props.items.reduce(function(previous, c, ind) {
        var next = previous.concat(<[Item id={c.id} />]);
        if (ind == 3) { next.push(<hr); }
        return next;
    }.bind(this), [])}
</div>