我正在创建一个 slider 并使用 prop. 向其中添加数据。每个幻灯片 div 都有一个标题和说明。我还想为每个 div 提供不同的图像背景。是否可以使用 props 将背景图像添加到 div 中?
这是我的方法,但它不起作用:
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
属性。要将其与 props
一起使用,您需要使用 string-interpolation
。
查看工作沙箱:https://codesandbox.io/s/solitary-lake-fey03
function Slide(props) {
return (
<div className="slide" style={{ backgroundImage: `url(${props.image})` }}>
<h3> {props.heading} </h3>
<p> {props.description} </p>
</div>
);
}
export default Slide;
关于javascript - 使用 props 添加背景到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57723194/