正在创建一个react
组件,当background-color
为null
时,我尝试使用css
属性来返回,正如我在这里看到的一篇SO文章所示。 该代码仅在有任何图像时才起作用,但当没有图像时,它不会返回到background-color
,并显示错误undefined:1GET http://localhost:3000/undefined404(Not Found)
。 我错过了什么?
const BoxModule = ({
backgroundColor,
BackgroundImage,
}) => {
const imageFormats = BackgroundImage?.formats;
const imageSrc = formatImage({ formats: imageFormats });
if (!BackgroundImage || !BackgroundImage?.url) {
return null;
}
return (
<Section
backgroundColor={backgroundColor}
backgroundImageUrl={imageSrc}
>
...
</Section>
);
export default BoxModule;
const Section = styled(Section)`
background-color: ${(p) => p.backgroundColor};
background-image: ${(p) => `url('${p.backgroundImageUrl}')`};
background-repeat: no-repeat;
`;
[更新的错误跟踪]
我只能看到如下所示的错误:
出现此错误是否因为代码试图处理图像
,该图像由于空
值而失败,因此无法返回到bacground-color
?
您可以检查p.BackgroundImageUrl
是否已定义或为空。
background-image: ${(p) => p.backgroundImageUrl ? `url('${p.backgroundImageUrl}')` : none};