React to render dynamically a certain number of co

2019-07-31 17:40发布

问题:

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.