我想渲染基于数字常量的组件。
对于数组,这不是问题,但我没有常数的解决方案。
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>
));
有关创建数组的其他方法,请参阅相关问题。
您可以使用数组构造函数
{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)
定义一个数组,该数组包含基于常量的多个项。如果您有一个动态数量的项目作为道具,您可以执行以下操作(当numberOfItems
发生变化时,使用React.useMemo只生成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>
)}
)