Javascript 使用道具向div添加背景
我正在创建一个滑块,并使用prop向其中添加数据。每个幻灯片分区都有标题和说明。我还想给每个div提供不同的图像背景。是否可以使用道具向div添加背景图像 以下是我的方法,但它不起作用:Javascript 使用道具向div添加背景,javascript,node.js,reactjs,ecmascript-6,Javascript,Node.js,Reactjs,Ecmascript 6,我正在创建一个滑块,并使用prop向其中添加数据。每个幻灯片分区都有标题和说明。我还想给每个div提供不同的图像背景。是否可以使用道具向div添加背景图像 以下是我的方法,但它不起作用: const slideData = [ { id: 1, heading: "First Heading", description: "A short description of the service goes here", imag
const slideData = [
{
id: 1,
heading: "First Heading",
description: "A short description of the service goes here",
image: './images/candle.jpg'
},
{
id: 2,
heading: "Second Heading",
description: "A short description of the service goes here",
image: './images/candle.jpg'
},
{
id: 3,
heading: "Third Heading",
description: "A short description of the service goes here",
image: './images/candle.jpg'
},
{
id: 4,
heading: "Fourth Heading",
description: "A short description of the service goes here",
image: './images/candle.jpg'
}
]
export default slideData
和子组件
import React from 'react';
function Slide(props) {
return (
<div className="slide" style={{background: props.image}}>
<h3> { props.heading} </h3>
<p> { props.description} </p>
</div>
);
}
export default Slide;
是的,你可以,你实际上是在寻找backgroundImage属性。要将其用于道具,需要使用字符串插值 请参见工作沙箱:
也许这个代码片段会对您有所帮助
style={{ backgroundImage: `url(${props.image})`
你检查过背景图像的路径是否正常吗?@TalhaMunir我添加了一些cat图片和实际的滑块功能,如果你需要参考:
style={{ backgroundImage: `url(${props.image})`