我听说过 react 模板,但我仍然想知道是否可以制作一流的 ForEach 组件。
我的最终目标是让这样的东西更具可读性:
<ul>
{list.map(function(item, i) {
return <li>{item}</li>;
})}
</ul>
// instead?
<ul>
<ForEach items="{list}">
<li>{item}</li>
</ForEach>
</ul>
这是我第一次认真尝试传递 Prop :
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}
将在Element.render
内部工作,但这不是我想要的 - 我希望能够向 Element
传递一些插入当前项目的表达式。
这在 React 中是不可能的吗?或者有什么方法可以让 ForEach
组件将当前项/索引等状态传递给嵌套元素?
更新 使用 ES6 箭头函数,我可以显着提高可读性。一组花括号和 return
一起消失(如果您在循环内引用 this
,可能还有 .bind(this)
) .
<ul>
{list.map((item, i) =>
<li>{item}</li>
)}
</ul>
这对于解决 map
行的语法笨拙问题有很大帮助。
最佳答案
我的方法是让 ForEach
期望为每个项目调用一个函数子函数,并简单地将一个 react 元素注入(inject)到渲染中。
它的用法如下:
render: function() {
return (
<ForEach items={['foo', 'bar', 'baz']}>
{function (item) {
return (
<Element>{item}</Element>
)
}/*.bind(this)*/} // optionally use this too
</ForEach>
)
}
如果你使用ES6 Arrow Functions,看起来会更好。 :
render() {
return (
<ForEach items={['foo', 'bar', 'baz']}>
{(item) => // bind is not needed with arrow functions
<Element>{item}</Element>
}
</ForEach>
)
}
<小时/>
现在,实际实现 ForEach
:
var ForEach = React.createClass({
getDefaultProps: function(){
return {
element: 'ul',
elementProps: {}
};
},
render: function(){
return React.createElement(
// Wrapper element tag
this.props.element,
// Optional props for wrap element
this.props.elementProps,
// Children
this.props.items.map(this.props.children, this)
);
}
});
很简单!我发现的一个警告是 key
属性需要由迭代器函数手动设置(可能使用 key={index}
)
看看我的basic example
关于reactjs - React.js - ForEach 作为一流组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681136/