简体   繁体   中英

Changing the URL of a background image in React

I'm trying to change background image by accessing DOM and changing css property like so:

///anotherweathermap.js

const changePic = () => {
    document.getElementById('bckgAnother').style.backgroundImage = "url(../img/kaunas.jpg)";
}

The image will not load在此处输入图像描述 but when I put the img path in css, the img path is different:

在此处输入图像描述
If I insert the same path, the one with static/media.., the DOM manipulation works. This is the order of files: 在此处输入图像描述

Relative URLs in CSS images are computed between the location of the style sheet (which will be the URL of the webpage itself for inline CSS) and the URL of the image.

They have nothing to do with either:

  • The URL of the JS file
  • The location on the file system of the JS file
  • The location on the file system of the image (except in so far as that is used to determine the URL it gets)

Since you are using React, you will need to import the image and then use the imported value of it to get the URL.

You should change your logic to set the value based on state and avoid direct DOM manipulation.

import Default from '../img/default.jpg';
import Kaunas from '../img/kaunas.jpg';


const AnotherWeatherMap = (props) => {
    const [background, setBackground] = useState(Default);

    const css = {
        backgroundImage: `url(${background})`
    };

    return (<div style={css}>
        <button onClick={ () => setBackground(Kaunas) }>Change background<button>
    </div>);
};

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