React - 动态渲染一定数量的组件

2024-01-26

我想根据用户获得的积分数显示组件星号(MUI 组件)的数量(this.state.points).

我不知道该怎么做。

import React, { Component } from "react";
import { Star } from "@material-ui/icons";

Points extends Component {
  constructor(props) {
  super(props);
    this.state = {
      points: 6
    };
  }

  render() {
     return (
       <div>
         <p>
           + {this.state.points} points
           <Star />
         </p>
       </div>
     );
    }
  }

export default Points;

您可以使用Array.fill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill创建新数组this.state.points空槽的数量,然后用<Star />像这样的组件:

import React, { Component } from "react";
import { Star } from "@material-ui/icons";

class Points extends Component {
  constructor(props) {
    super(props);
    this.state = {
      points: 6
    };
  }

  render() {
    return (
      <div>
        <p>
          + {this.state.points} points
          // This is where the magic happens
          {Array(this.state.points).fill(<Star />)}
        </p>
      </div>
    );
  }
}

export default Points;

这是一个工作沙箱:https://codesandbox.io/s/vj3xpyn0x0 https://codesandbox.io/s/vj3xpyn0x0

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

React - 动态渲染一定数量的组件 的相关文章