在ReactJS中使用CSS文件中的图像 [英] Use images in CSS files with ReactJS

查看:35
本文介绍了在ReactJS中使用CSS文件中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ReactJs项目的 src/assets/images 文件夹中有一个图像.如何在CSS文件中将其用作背景图像而不使用相对路径?

I have an image inside src/assets/images folder in my ReactJs project. How can I use it in a CSS file as background-image without use relative paths?

我在 compilerOptions.baseUrl src 文件夹的 jsconfig.json 中添加了代码,因此可以在js文件中进行操作:

I added in jsconfig.json the src folder in compilerOptions.baseUrl so in js files I can do:

import logo from 'assets/images/logo.svg'
<img src={logo} />

但是css文件呢?我有几个文件夹,我想避免使用类似

but what about css files? I have several folders and I'd like to avoid ugly strings like

背景图片:url(../../../assets/images/logo.svg)

我正在使用React 16.8.6

I'm using React 16.8.6

我使用了create-react-app,所以我没有暴露webpack文件,应该避免弹出.

I used create-react-app, so I haven't webpack files exposed and the ejection shoud be avoided.

推荐答案

考虑将Webpack用于静态资产捆绑包,本教程可能会帮助您: https://webpack.js.org/guides/asset-management/

Consider using Webpack for static assets bundle, this tutorial might help you: https://webpack.js.org/guides/asset-management/

基本上,分3个步骤:

  1. 首先对所需图像的任何扩展名使用文件加载器.

  1. First use file-loader for any extensions of images you want.

导入您的图片在js文件中.

import your image in the js file.

现在CSS文件可以简单地获取简化的URL

Now CSS file can simply get the simplified url

更新:由于您不想修改webpack配置文件,因此您可以考虑将图像内置.通过不为图像创建另一个http请求(仅用于小尺寸图像)来提高性能

Update: Since you don't want to modify the webpack config file, you might consider making your image inline. It improves performance by not creating another http request for the image(only for small size images)

这篇关于在ReactJS中使用CSS文件中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆