React.js - ForEach 作为一流组件?

2024-02-10

我听说过反应模板,但我仍然想知道是否可以制作一流的 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.


我的方法是ForEach期望为每个项目调用一个子函数,并简单地将一个反应元素注入到渲染中。

它会像这样使用:

render: function() {
  return (
    <ForEach items={['foo', 'bar', 'baz']}>
      {function (item) {
        return (
          <Element>{item}</Element>
        )
      }/*.bind(this)*/} // optionally use this too
    </ForEach>
  )
}

如果你使用的话,这看起来会更好ES6 箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/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)
      );
   }
});

很简单!我发现的一个警告是keyprop 需要通过迭代器函数手动设置(可能使用key={index})

看看我的基本示例 https://jsfiddle.net/mattsturgeon/8ontg9jc/2/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React.js - ForEach 作为一流组件? 的相关文章

随机推荐