【问题标题】:How to use API returned image for background image in media query?如何在媒体查询中使用 API 返回的图像作为背景图像?
【发布时间】:2019-04-27 16:47:39
【问题描述】:

我的 style.scss 中有这个:

.myComponent {

    &__pic {

        // some other styles

        @media (max-width: 767px),
          (-webkit-min-device-pixel-ratio: 2),
          (min-resolution: 192dpi) {
          background-image: url({this needs to come from API});
        }

    }

}

如果只是默认的背景图片,我知道该怎么做,像这样:

<div className="col-md-8">
    <div className="myComponent__pic" style={{
        backgroundImage: `url(${someObject.someImage})`
    }} />
</div>

但是如何在样式表之外指定@media 样式,以便我可以为其提供来自API 的图像(someObject.someImage2x)?

【问题讨论】:

标签: javascript css reactjs sass media-queries


【解决方案1】:

您可能希望使用 CSS 变量作为解决方法。

let imageQuery = {
  --backgroundImage-2x: `url(${someObject.someImage2x})`,
  --backgroundImage-1x: `url(${someObject.someImage1x})`
}

<div className="col-md-8">
    <div className="myComponent__pic" style={imageQuery} />
</div>
.myComponent {

    &__pic {
        --backgroundImage-2x: "";
        --backgroundImage-1x: "";
        // some other styles
        
        background-image: var(--backgroundImage-1x);
        
        @media (max-width: 767px),
          (-webkit-min-device-pixel-ratio: 2),
          (min-resolution: 192dpi) {
          background-image: var(--backgroundImage-2x);
        }

    }

}

【讨论】:

    猜你喜欢
    • 2014-08-14
    • 2015-06-08
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 2014-01-26
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多