可以复制或合并JSX吗? [英] Possible to multiply or concat JSX?

查看:58
本文介绍了可以复制或合并JSX吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React和Font Awesome来创建一行星星.我有一个函数,该函数需要一个数字并产生那么多星星.我正在尝试找到在React组件中执行此操作的最佳方法.基本上,我需要将JSX元素乘以一个数字,以使其根据传入的内容动态重复:

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;
  };

如果JSX是字符串,则可以使用,但是因为不是,所以我无法在其上调用repeat(错误表示star不是函数).我可以将其用单引号引起来",然后替换为单引号,但想知道是否有更好的解决方案吗?谢谢.

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.

推荐答案

尝试如下操作:

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

这篇关于可以复制或合并JSX吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆