如何通过数据映射来显示样式组件道具的图像



所以我有一个图像滑块,它可以映射数据并显示我的图像

{SliderData.map((slide, index) => {
return (
<Section>
<h1>{slide.title}</h1>
<Image src={slide.image} alt={slide.alt} />
</Section>
);
})}

我的数据文件看起来像这个

export const SlideData = [
{
title: 'title',
alt: 'alt',
image: './images/image-1.jpg'
},
{
title: 'title 2',
alt: 'alt 2',
image: './images/image-2.jpg'
},
]

我的问题是如何将图像传递到一个样式化的组件中,而不是在我的JSX中对其进行硬编码?

const Section = styled.section`
background: url(${image});
`

像这样的东西,我只是把图像传递到有样式的组件中。我不明白的是,如果我将数据传递到样式组件中,那么每张幻灯片的数据将如何映射?

我不知道如何读取所有图像的数据文件,因为图像值被传递到样式组件background属性中?

我想通过这个方法传递我的滑块图像,因为它允许我以一种特定的方式设计设计,而当我将其硬编码到我的JSX中时,我无法做到这一点。

有什么想法吗?

这可以解决

<Section bg={bgPath} alt="logo" />
const Section= styled.section`
background-image: url(${(props) => props.bg});   
`;

好吧,我想这就是你所说的:

<Section image={image}></Section>

然后:

const Section = styled.section`
background: url(${(props) => props.image || 'fallback-image.jpg' }) center;

文件:

  1. https://styled-components.com/docs/basics#passed-支柱

最新更新