[英]Issue with displaying background image in a div with REACT
I am trying to display a background image in a div
and though it works fine for a standard img
tag I can't make it work for the div
. 我正在尝试在
div
显示背景图像,尽管对于标准img
标签它可以正常工作,但我无法使其适用于div
。 What am I doing wrong? 我究竟做错了什么? Below is where I import the image:
下面是我导入图像的位置:
import imgPackage from '../img/package.png';
And below is the 2 pieces of code - div
doesn't display anything and img
works fine. 下面是2段代码
div
不显示任何内容,并且img
工作正常。
<div
style={{
height: '50px',
width: '50px',
backgroundImage: 'url(${ imgPackage })'
}}
/>
<img src={imgPackage} alt="Smiley face" height="42" width="42" />
In the div backgroundImage
I tried the following and none worked 在div
backgroundImage
我尝试了以下操作,但没有任何效果
backgroundImage: 'url(${ imgPackage })'
backgroundImage: 'url('+{ imgPackage }+')'
backgroundImage: 'url(../img/package.png)'
What am I doing wrong? 我究竟做错了什么? Thanks!
谢谢!
You're trying to use a template literal but you're using single quotes instead of back-ticks. 您正在尝试使用模板文字,但您使用的是单引号而不是反引号。
Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes.
模板文字用反引号(``)(重音符)括起来,而不是双引号或单引号。 Template literals can contain placeholders.
模板文字可以包含占位符。 These are indicated by the dollar sign and curly braces (${expression}).
这些由美元符号和大括号($ {expression})表示。
<div
style={{
...,
backgroundImage: `url(${imgPackage})`
}}
/>
Try using this. 尝试使用这个。 on single quotes you cant use ${} syntax.
单引号上不能使用$ {}语法。 it can be used with `` back tick
它可以和``back tick一起使用
backgroundImage: `url(${ imgPackage })`
backgroundImage: 'url('+ imgPackage +')'
Any of your tries are wrong. 您的任何尝试都是错误的。 Following variants will work after some changes:
进行一些更改后,以下变体将起作用:
If you prefer ES6 template literals you should use back-ticks quotes for them: 如果您更喜欢ES6模板文字,则应为其使用反引号引起来:
backgroundImage: `url(${ imgPackage })`;
If you prefer plain strings no need to add extra single quotes inside url()
: 如果您喜欢纯字符串,则无需在
url()
内添加额外的单引号:
backgroundImage: 'url( + { imgPackage } + )';
This case might working with appropriate url-loader from you webpack etc. Consider to use 2 examples above. 这种情况可能与您的webpack等中的适当url-loader一起使用。请考虑使用上面的2个示例。
backgroundImage: 'url(../img/package.png)'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.