如何在 for 循环中渲染反应组件?

How to render react components in a for loop?

我想根据数字常量渲染组件。

使用数组不会有问题,但我没有常量的解决方案。

  const numberOfItems = 4;

  return (
      {/* The for loop should be here, with which 4 <Grid> components should then be rendered */}
        <Grid item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
        </Grid>
   )

您可以创建一个数组并映射它:

const numberOfItems = 4;

return [...Array(numberOfItems).keys()].map((key) => (
  <Grid key={key} item xs={12} sm={6}>
    <TextField />
  </Grid>
));

有关创建数组的其他方法,请参阅 related question

您可以使用 Array 构造器

{Array.from(new Array(4)).map((_, i) => (
  <Grid key={i} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
))}

您可以使用new Array(numberOfItems).fill(0) 来定义一个数组,其中包含基于常量的多个项目。如果你有一个动态数量的项目作为道具,你可以执行以下操作(使用 React.useMemo 仅在 numberOfItems 更改时生成一次 itemsArray):

const Component = ({ numberOfItems }) => {

  const itemsArray = React.useMemo(() => {
     return new Array(numberOfItems).fill(0);
  }, [numberOfItems]);
    
  return (
   <div>
    {itemsArray.map((_, index) => (
       <Grid key={index} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
       </Grid>
    ))}
   </div>
  );
}

否则,定义一个常量:

const numberOfItems = 4;
const itemsArray = new Array(numberOfItems).fill(0);

const Component = () => {

  return (
   <div>
    {itemsArray.map((_, index) => (
       <Grid key={index} item xs={12} sm={6}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
       </Grid>
    ))}
   </div>
  );
}

如果你使用 Lodash 之类的东西,你可以使用 _.times:

  return (
      {_.times(4, index =>
        <Grid item xs={12} sm={6} key={index}>
          <TextField
            required
            id="quadrant-one"
            name="quadrant-one"
            label="Quadrant 1"
            fullWidth
          />
        </Grid>
      )}
   )