我试图通过 JSX React 中的内联 css 添加背景图像,但它没有更新

import React from "react";

import ReactDOM from "react-dom";


const customStyle = {

  color : "red"


}


const dStyle = {

  backgroundImage : "https://wallpapercave.com/wp/wp2771916.jpg", // unable to view this image as background-image

}


ReactDOM.render(

<div style = {dStyle}>

  <h1 style = {customStyle}>Hello World!

  </h1>

  </div>, document.getElementById("root"));

我尝试通过永恒的样式来完成上述操作,但它发生了,但通过内联 css 我无法获取图像。


慕码人2483693
浏览 173回答 3
3回答

大话西游666

在内联CSS中只需添加url(...)如下内容import React from "react";import ReactDOM from "react-dom";const customStyle = {&nbsp; color : "red"}const dStyle = {&nbsp; backgroundImage : "url(https://wallpapercave.com/wp/wp2771916.jpg)",}ReactDOM.render(<div style = {dStyle}>&nbsp; <h1 style = {customStyle}>Hello World!&nbsp; </h1>&nbsp; </div>, document.getElementById("root"));

慕容708150

解决方案一:<div style={{ backgroundImage: `url(require("https://wallpapercave.com/wp/wp2771916.jpg"))` }}>解决方案2:import React from "react";import Background from 'https://wallpapercave.com/wp/wp2771916.jpg';import ReactDOM from "react-dom";const customStyle = {&nbsp; color : "red"}const dStyle = {&nbsp; backgroundImage: "url(" + { Background } + ")" // unable to view this image as background-image}ReactDOM.render(<div style = {dStyle}>&nbsp; <h1 style = {customStyle}>Hello World!&nbsp; </h1>&nbsp; </div>, document.getElementById("root"));

BIG阳

这将有助于:首先将 imageUrl 存储在变量中,然后使用style属性,如下所示:const TestingImage = () => {&nbsp; const imageUrl = "https://wallpapercave.com/wp/wp2771916.jpg";&nbsp; return (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <div&nbsp; &nbsp; &nbsp; &nbsp; style={{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundImage: `url(${imageUrl})`,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height: "400px",&nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; ></div>&nbsp; &nbsp; </>&nbsp; );};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript