简体   繁体   中英

How to use API returned image for background image in media query?

I have this in my 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});
        }

    }

}

I know how to do if it's just the default background image, like so:

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

But how do I specify the @media style outside the stylesheet so that I can give it the image ( someObject.someImage2x ) coming from the API?

You might want to use CSS variables as a workaround.

 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); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM