reactjs – React.js – ForEach作为一流的组件?
|
我听说过react-templates,但我仍然想知道有可能制作出一流的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.props.item设置创建克隆元素,但是因为{this.props.item}是在其他封闭组件的render方法的上下文中计算的,所以这不是克隆的Element组件 – 它是ForEach的父级. {this.props.item}将在Element.render中工作,但这不是我想要的地方 – 我希望能够将Element插入当前项目的表达式. 这在React中是不可能的,还是有某种方法可以让ForEach组件将当前项/索引的状态传递给嵌套元素? 更新我可以通过ES6箭头功能显着提高可读性.一组曲线随着返回一起消失(如果你在循环中引用它,也可能还有一个.bind(this)). <ul>
{list.map((item,i) =>
<li>{item}</li>
)}
</ul>
这对于帮助处理地图线的语法笨拙有很大帮助.
我的方法是让ForEach期望为每个项调用一个函数子,并简单地将一个react元素注入到渲染中.
它将使用这样的东西: render: function() {
return (
<ForEach items={['foo','baz']}>
{function (item) {
return (
<Element>{item}</Element>
)
}/*.bind(this)*/} // optionally use this too
</ForEach>
)
}
如果您使用ES6 Arrow Functions,这看起来会更好: render() {
return (
<ForEach items={['foo','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)
);
}
});
很简单!我发现的一个警告是,关键道具需要由itterator函数手动设置(可能使用key = {index}) 看看我的basic example (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
