[英]How to integrate Javascript variable into ReactJS JSX style element
I have a javascript array of image sources.我有一个 javascript 图像源数组。 Now I need to implement each of the image source in individual box background.
现在我需要在单独的框背景中实现每个图像源。 I am trying to put the array element into React JSX style element like below (demo code)
我正在尝试将数组元素放入 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>)
Hope I can make you understand my problem.希望我能让你明白我的问题。 Please help, any alternative way is always welcome.
请帮助,任何替代方式总是受欢迎的。 thank you in advance
先感谢您
For
loop won't work directly in render
function. For
循环不能直接在render
function 中工作。 you can use map
instead您可以改用
map
images.map((image, index) => (
<Box key={index} style={{background: `url(${image})`}}>
Some code goes here.......
</Box>
))
Check this example: https://codesandbox.io/s/broken-frost-4iz90检查这个例子: https://codesandbox.io/s/broken-frost-4iz90
You can check this as well: Loop inside React JSX你也可以检查一下: Loop inside React JSX
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.