提问者:小点点

背景图像为空时回退背景颜色


正在创建一个react组件,当background-colornull时,我尝试使用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


共1个答案

匿名用户

您可以检查p.BackgroundImageUrl是否已定义或为空。

background-image: ${(p) => p.backgroundImageUrl ? `url('${p.backgroundImageUrl}')` : none};