我听说过反应模板,但我仍然想知道是否可以制作一流的 ForEach 组件。
我的最终目标是使这样的东西更具可读性:
<ul>
{list.map(function(item, i) {
return <li>{item}</li>;
})}
</ul>
// instead?
<ul>
<ForEach items="{list}">
<li>{item}</li>
</ForEach>
</ul>
这是我第一次认真尝试传递道具:
var ForEach = React.createClass({
render: function(){
return (
<ul>
{this.props.items.map(function(item, i) {
return React.Children.map(this.props.children, function(child) {
return React.addons.cloneWithProps(child, {item: item})
})
}.bind(this))}
</ul>
);
}
});
var Element = React.createClass({
render: function(){
return (
<li>{this.props.children}</li>
);
}
});
// usage within some other React.createClass render:
<ForEach items={['foo', 'bar', 'baz']}>
<Element>{this.props.item}</Element>
</ForEach>
我遇到的挑战是什么this
指着。通过使用调试器单步执行,我可以看到我正在使用以下命令创建克隆元素this.props.item
设置,但是因为{this.props.item}
在其他一些封闭组件的上下文中进行评估render
方法,this
不是克隆的Element
组件——它是ForEach
的父母。
{this.props.item}
will在里面工作Element.render
但这不是我想要的 - 我希望能够手Element
一些插入当前项目的表达式。
这在 React 中是不可能的吗?还是有什么方法可以让我做到这一点?ForEach
组件将当前项目/索引等状态传递给嵌套元素?
UPDATE使用 ES6 箭头函数,我可以显着提高可读性。一组卷发消失了,随着return
(也可能是.bind(this)
如果你参考this
循环内)。
<ul>
{list.map((item, i) =>
<li>{item}</li>
)}
</ul>
这对于解决语法笨拙的问题有很大帮助map
line.