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

查看:36
本文介绍了如何渲染重复的 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 中为什么 for 循环在 JSX 语法中永远不可能;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天全站免登陆