我正在寻找某种方法来返回子级原始数据而不将它们包装在 div 中,以下方法不起作用:
render: function () {
return this.props.children
)
}
这样做:
render: function () {
return (
<div>
{this.props.children}
</div>
)
}
如何编辑子项
并提供一组不包装在另一个元素中的新子项?
最佳答案
这是操作 this.props.children
的方法:
top-level-api.html#react.children
至于提供一组未包装的子项,在Reactjs中是不可能且不合理的。您可能认为您正在渲染一个组件,而不是一个列表或其他东西。 official explanation像这样:
<小时/>Note: One limitation: React components can only render a single root node. If you want to return multiple nodes they must be wrapped in a single root.
好吧,当只有一个 child 时,你肯定可以返回this.props.children
。我重新检查了您的代码片段,发现您可能存在语法错误,return this.props.children
这是我自己的测试,它渲染正确:
var Test = React.createClass({
render(){
return this.props.children
}
})
React.render(
<Test><div>hello world</div></Test>,
document.getElementById("test")
);
<小时/>
更新: 在我看来,您应该避免像我上面那样这样做,因为我相信这会使您的组件容易受到攻击。
关于javascript - 返回元素的渲染而不换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707526/