如何渲染重复的React元素? [英] How can I render repeating React elements?

查看:349
本文介绍了如何渲染重复的React元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一些代码来渲染ReactJS中的重复元素,但我讨厌它有多丑。

I've written some code to render repeating elements in ReactJS, but I hate how ugly it is.

render: function(){
  var titles = this.props.titles.map(function(title) {
    return <th>{title}</th>;
  });
  var rows = this.props.rows.map(function(row) {
    var cells = [];
    for (var i in row) {
      cells.push(<td>{row[i]}</td>);
    }
    return <tr>{cells}</tr>;
  });
  return (
    <table className="MyClassName">
      <thead>
        <tr>{titles}</tr>
      </thead>
      <tbody>{rows}</tbody>
    </table>
  );
} 

有没有更好的方法来实现这个目标?

Is there a better way to achieve this?

(我想在模板代码中嵌入 for 循环,或类似的方法。)

(I would like to embed for loops within the template code, or some similar approach.)

推荐答案

您可以将表达式放在大括号内。请注意,在编译的JavaScript中,为什么在JSX语法中永远不可能有 for 循环; JSX相当于函数调用和含糖函数参数。只允许使用表达式。

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(另外:请记住将 key 属性添加到循环内呈现的组件中。)

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

这篇关于如何渲染重复的React元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆