Possible to multiply or concat JSX?

微笑、不失礼 提交于 2020-01-11 10:47:31

问题


I'm using React along with Font Awesome to create a row of stars. I have a function that takes a number and produces that many stars. I'm trying to find the best way to do this within a react component. Basically, I need to multiply the JSX element by a number to get it to repeat dynamically based on what's passed in:

reviewStars(num) {
    const star = <i className="fa fa-star" aria-hidden="true"></i>;
    const getStarCount = star.repeat(num);
    return getStarCount;
  };

If the JSX was a string, this would work, but because it's not, I can't call repeat on it (error says star is not a function). I could wrap it in single quotes '' and then replace those, but wondering if there is a better handle to this? Thanks.


回答1:


Try something like this:

reviewStars(num) {
  let stars = [];
  for(let i= 0; i < num; i++) {
    stars.push(<i key={i} className="fa fa-star" aria-hidden="true"></i>);
  }
  return (
    <div>{stars}</div>
  );
};

edit: remember to add key to lists




回答2:


In order to maintain validity of JSX, you would first need to wrap sibling elements in a parent element, either a <span> or a <div>.

Afterwards you would have to loop num times and repeat your JSX for the star, accumulating it in a variable that you will return inside that wrapper.

Something like this should do the trick for you

reviewStars(num) {
   let stars = [];

   for (let i = 0; i < num; i++) {
       stars.push(<i className="fa fa-star" aria-hidden="true" key={i} />;
   }

   return (
       <span>
          {stars}
       </span>
   );
};



回答3:


Array.from() method creates an array with specified length. See MDN here.

<div>
{ Array.from({ length: num }, (_, i) =>
    <i key={i} className="fa fa-star" aria-hidden="true"></i>) }
</div>

The mapper assigns a key from the second argument (index) to each child element.



来源:https://stackoverflow.com/questions/38001569/possible-to-multiply-or-concat-jsx

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