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

时间:2018-06-17 15:44:00

标签: javascript reactjs icons state material-ui

我想根据用户获得的点数(this.state.points)显示一些组件Star(material-ui组件)。

我不知道该怎么做。

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;

3 个答案:

答案 0 :(得分:7)

您可以使用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

答案 1 :(得分:2)

试试这个

     Distance               
Node            0     1     2   
Time                            
0             27.0  54.0  97.0  
60            22.0  49.0  92.0 
Difference     5.0  5.0   5.0

答案 2 :(得分:1)

这可能会有所帮助:

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

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

  getUserStars() {
    let i = 0;
    let stars = [];
    while (i < this.state.points) {
      i++;
      stars.push(<Star />);
    }
    return stars;
  }

  render() {
    return <div>{this.getUserStars(this.state.points)}</div>;
  }
}

export default Points;

你只需要迭代循环并在数组中收集星星并在渲染中调用该函数,这样每当状态更新时该函数将调用并且星星将更新。