为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕码人2483693 2023-09-28 17:23:11
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 我无法获取图像。
查看完整描述

3 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

在内联CSS中只需添加url(...)如下内容


import React from "react";

import ReactDOM from "react-dom";


const customStyle = {

  color : "red"


}


const dStyle = {

  backgroundImage : "url(https://wallpapercave.com/wp/wp2771916.jpg)",

}


ReactDOM.render(

<div style = {dStyle}>

  <h1 style = {customStyle}>Hello World!

  </h1>

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


查看完整回答
反对 回复 2023-09-28
?
慕容708150

TA贡献1831条经验 获得超4个赞

解决方案一:


<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 = {

  color : "red"


}


const dStyle = {

  backgroundImage: "url(" + { Background } + ")" // unable to view this image as background-image

}


ReactDOM.render(

<div style = {dStyle}>

  <h1 style = {customStyle}>Hello World!

  </h1>

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


查看完整回答
反对 回复 2023-09-28
?
BIG阳

TA贡献1859条经验 获得超6个赞

这将有助于:


首先将 imageUrl 存储在变量中,然后使用style属性,如下所示:


const TestingImage = () => {

  const imageUrl = "https://wallpapercave.com/wp/wp2771916.jpg";

  return (

    <>

      <div

        style={{

          backgroundImage: `url(${imageUrl})`,

          height: "400px",

        }}

      ></div>

    </>

  );

};


查看完整回答
反对 回复 2023-09-28
  • 3 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信