如何在背景图像css文件上正确写入react 17.0.1?

这是我尝试过的 3 个选项


.bg {

    background-image: url("/images/icons/courier.png")

}

.bg {

    background-image: url("./images/icons/courier.png")

}

.bg {

    background-image: url("../images/icons/courier.png")

}

icon is located: /public/images/icons/... 请参阅此处了解更多详情


给出这个错误:


./src/components/header/header.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss !./src/components/header/header.css) 错误:无法解析“E:\New project\yamboo\src\components\header”中的“/images/icons/courier.png”


前面这段代码 -->


.bg {

    background-image: url("/images/icons/courier.png")

}

在 React 版本 16.13.1 中工作正常


请帮忙,我将不胜感激!提前致谢!!!


慕无忌1623718
浏览 93回答 2
2回答

沧海一幻觉

暂时我已经通过将“package.json”文件中的“react-scripts”版本更改为3.4.4来解决该问题。

一只萌萌小番薯

const divStyle = {&nbsp; color: 'blue',&nbsp; backgroundImage: 'url(' + imgUrl + ')',};function HelloWorldComponent() {&nbsp; return <div style={divStyle}>Hello World!</div>;}style 属性接受具有驼峰命名属性的 JavaScript 对象,而不是 CSS 字符串。这与DOM风格的JavaScript属性一致,效率更高,并且可以防止XSS安全漏洞。import React from "react";import hcbgImage from "./hcbg.jpg";function App() {&nbsp; return (&nbsp; &nbsp; &nbsp; <div&nbsp; &nbsp; &nbsp; &nbsp; class="bg_image"&nbsp; &nbsp; &nbsp; &nbsp; style={{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundImage: 'url('+hcbgImage+')',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundSize: "cover",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; height: "100vh",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; color: "#f5f5f5"&nbsp; &nbsp; &nbsp; &nbsp; }}&nbsp; &nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; <h1>This is Text on top</h1>&nbsp; &nbsp; &nbsp; </div>&nbsp; );}export default App;在上面的示例中,我们导入图像并将其路径存储在名为 hcbgImage 的变量中。如果我们通过控制台记录该变量,我们会得到类似 /static/media/hcbg.d1e1f550.jpg 的内容。这是React.js 的图像路径。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript