如何将Javascript变量集成到ReactJS JSX样式元素中



我有一个图像源的javascript数组。现在我需要在单独的盒子背景中实现每个图像源。我正在尝试将数组元素放入React JSX风格的元素中,如下所示(演示代码(

const box = []
for(const [index, image] of images.entries()) {
box.push(
<Box key={index} style={{background: 'url(image)'}}>
Some code goes here.......
</Box>
)}
return(<div>{box}</div>)

希望我能让你理解我的问题。请帮忙,任何其他方式都是受欢迎的。提前感谢

For循环不会直接在render函数中工作。你可以用map代替

images.map((image, index) => (
<Box key={index} style={{background: `url(${image})`}}>
Some code goes here.......
</Box>
))

检查此示例:https://codesandbox.io/s/broken-frost-4iz90

你也可以检查一下:React JSX 内部的环路

希望这能有所帮助!

最新更新