React to render dynamically a certain number of components

 ̄綄美尐妖づ 提交于 2019-12-11 05:09:44

问题


I would like to display a number of the component Star (material-ui component) based on the number of points the user has earned (this.state.points).

I don't know how to do this.

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;

回答1:


You can use Array.fill to create new Array with this.state.points number of empty slots which you then fill with the <Star /> component like so:

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;

Here is a working Sandbox : https://codesandbox.io/s/vj3xpyn0x0




回答2:


Try this

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

       {Array.from(Array(this.state.points)).map((x, index) => <Star key={index} />)}
     </p>
    </div>
  );
  }
}

export default Points;



回答3:


This might help:

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;

You just need to iterate an loop and collect stars in array and call that function in render so whenever state will get updated that function will call and stars will update.



来源:https://stackoverflow.com/questions/50898165/react-to-render-dynamically-a-certain-number-of-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!