如何动态渲染JSX组件X次? [英] How to dynamically render JSX component X times?

查看:56
本文介绍了如何动态渲染JSX组件X次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个React组件的render函数的简单示例:

Consider a simple example of the render function of a React component:

render () {
  const rowLimit = this.props.rowLimit ? this.props.rowLimit : 5
  return (
    <tbody>
      {row()}
      {row()}
      {row()}
      {row()}
      {row()}
    </tbody>
  )
}

当前rowLimit是没有用的..但是我想使用该数字来确定呈现了多少{rows()}个.有一种干净的方法可以做到这一点吗?

Currently rowLimit is useless.. but I would like to use that number to determine how many {rows()}s are rendered. Is there a clean way to do this?

使用for (let i = 0; i < rowLimit; i++)循环感觉很笨拙...我将奖励样式点,以寻求更好的解决方案

Using a for (let i = 0; i < rowLimit; i++) loop feels clunky... I will award style points for a better solution

注意:row()返回一个JSX元素

Note: row() returns a JSX element

推荐答案

您可以使用

You can use Array#from to convert limit to an array of rows:

class Tbody extends React.Component {
  render () {
    const { rowLimit = 5 } = this.props; // destructure with defaults instead of trinary
    
    return (
      <tbody>
      {
        Array.from({ length: rowLimit }, (_, k) => (
          <tr key={k}>
            <td>{k}</td>
          </tr>
        ))
      }
      </tbody>
    )
  }  
}

ReactDOM.render(
  <table>
    <Tbody />
  </table>,
  demo
);

td {
  border: 1px solid black;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="demo"></div>

这篇关于如何动态渲染JSX组件X次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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