【问题标题】:Fallback on background-color when background-image is null React当背景图像为空时回退背景颜色
【发布时间】:2020-07-13 14:19:56
【问题描述】:

创建一个React 组件,当background-imagenull 时,我尝试使用background-colorcss 属性回退,因为我可以看到其中一个SO 帖子here。该代码仅在有任何图像时才有效,但当没有图像时,它不会回退到background-color 并显示错误undefined:1 GET http://localhost:3000/undefined 404 (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;
`;

[更新的错误跟踪]

我只能看到如下所示的错误:

这个错误是因为代码正在尝试处理image,但由于null 值而失败,因此不会回退到bacground-color

【问题讨论】:

    标签: javascript css reactjs image-fallback


    【解决方案1】:

    实际上,代码足以回退到background-color。问题不是这个,是别的。因此,要回答这个特定问题,以下代码就足够了。甚至不需要对 background-image 进行空条件检查。

    const Section = styled(Section)`
    background-color: ${(p) => p.backgroundColor};
    background-image: ${(p) => `url('${p.backgroundImageUrl}')`};
    background-repeat: no-repeat;
    `;
    

    【讨论】:

      猜你喜欢
      • 2012-01-01
      • 2011-07-22
      • 1970-01-01
      • 2012-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      相关资源
      最近更新 更多