Next.js的background-image CSS属性无法加载图像。

76

我正在尝试访问一个静态图像,以便在React内的inline backgroundImage属性中使用。

我正在使用Reactjs和Next.js进行开发,然后遇到了使用Next.js添加图像的问题,但通过使用名为:Next.js + Images的图像加载器来解决了这个问题。

现在我可以使用普通的html img标签正常地添加图像。

例如:<img src={ img } /> 这样可以工作。

但是当我尝试添加CSS背景图像时,如下所示:

const team = (props) => {
const img = require("../../assets/images/security-team.jpg");
const styling = {
    backgroundImage: `url('${img}')`,
    width:"100%",
    height:"100%"
}
console.log(img);
return (
    <div className="team" style={styling}>

    </div>
);

}

这是控制台输出的结果:

/_next/static/images/security-team-449919af8999ae47eaf307dca4dda8e1.jpg

图片没有显示,也没有出现错误,然后我在浏览器中输入网站地址加上 console.log 的结果,图片出现了!


2
将代码第4行改为 backgroundImage: url('${img.src}') + .src - taotao
这里的".src"是做什么用的? - Sins97
23个回答

100

首先导入图像文件

import bg from '../../assets/images/security-team.jpg'

然后应用内联样式

style={{
      backgroundImage: `url(${bg.src})`,
      width: '100%',
      height: '100%',
    }}

4
谢谢!这应该是被接受的答案。 - taotao
3
.src是主要的东西。 - Azhar
1
@M.lslam:反引号帮了我。 - Jishnu V S
当您将图像作为背景导入时,它会返回一个对象。该对象将提供src属性,即图像的路径。您可以使用控制台日志在控制台上查看对象。 - M.Islam
如果您以这种方式导入图片,Next.js是否像使用<Image/>一样优化图片呢? - Stamatis Deliyannis
显示剩余2条评论

51

使用 next@11.0 时,我把我的图片放在 public 文件夹中,在样式文件中使用以下代码就可以了。

background-image: url('/image.svg');

29

这里所有的解决方案都不能充分利用NextJs自定义<Image>组件的主要优势,该组件默认提供了优化的响应式图像,并且具有巨大的好处。在我能够使用z-index来“伪造”CSS背景图片时,我会这样做。

然而,这种方法有一个限制,就是没有像CSS背景一样可以重复的选项。

请注意,此示例使用Tailwind CSS。

<div className="h-screen">
    <div className="absolute -z-10">
        <Image
            src="/some.jpeg"
            layout="fill"
            objectFit="cover"
            quality={100}
        />
    </div>
    <div> Some overlay things go in here </div>
</div>

2
你是对的。谢谢你的提醒。 - DINA TAKLIT
1
这很不错,使用<Image>组件是一个巨大的优势。 - Nick Howard
1
真的。但是背景图像具有您无法与图像一起使用的属性 https://developer.mozilla.org/zh-CN/docs/Web/CSS/background-image - Stamatis Deliyannis
我需要将inset-0添加到绝对定位的包装器中,这样它才能对我显示出来。<div className="absolute inset-0 -z-10"> - undefined

18

在styles/home.scss中的CSS文件

在public/bg-img.png中的图像文件

.content_bg {
    margin: 50px 0;
    background-image: url('../public/bg-img.png');
    height: 500px;
    background-size: cover;
    background-repeat: no-repeat;
}

1
这个解决方案是可行的,只是应该提到这些图像将在构建期间添加到捆绑包中,因此最好不要将它们放在 /public 文件夹中以避免混淆。 - bFunc
这个答案很好地解释了图片路径,大多数情况下这就是问题所在。谢谢。 - Nilupul Heshan
截至目前为止,这个方法是可行的。使用“../”来寻址路径是解决问题的关键。谢谢。 - Speedy11

15

这个包对我来说可行。

首先:

yarn add next-images

然后,在一个 next.config.js 文件中:

const withImages = require('next-images')
module.exports = withImages()

那么您可以这样做:

<div
  style={{
    backgroundImage: "url(" + `${require("./path-to-the-image")}` + ")",
    width: "100%",
    height:[HEIGHT OF THE IMAGE],
    backgroundRepeat: "no-repeat",
    backgroundSize: "cover"
  }}
>XXX</div>

有关next-images的更多信息:https://github.com/twopluszero/next-images


你能提及解决问题的方法并解释你对代码所做的修改吗? - Wassim Al Ahmad
2
我已经编辑了我的答案,展示了整个过程。这非常简单明了。 - thpo
没错,感谢您的合作。现在很清楚了。 - Wassim Al Ahmad

10
根据 nextjs 文档(https://nextjs.org/docs/basic-features/static-file-serving)所述,Next.js 可以在名为public的文件夹下提供静态文件(如图像)。然后可以通过基本 URL(/)从代码中引用public文件夹中的文件。
所以,从public文件夹引用图片的正确方式是:
CSS示例:
background-image: url('/your-image.jpg');

JSX示例:

import Image from 'next/image'
<Image src="/your-image.jpg" alt="Image description" width="64" height="64" />

有时开发人员需要将图像作为div的背景,我们能在这种情况下利用next/image吗? - Prav

5
当我使用JSX样式并添加绝对定位属性时,它可以正常工作。就像这样:
 <style JSX>{`
    .team {
        width:100%;
        height:100%;
        position:absolute;
        background: url('`+img+`') no-repeat;
    }
`}</style>

3
您也可以尝试使用“/static/images/security-team.jpg”而不需要导入,如果您将图像放在“/static/images/”文件夹中。 例如:
const styling = {
  backgroundImage: "url('/static/images/security-team.jpg')",
  width:"100%",
  height:"100%"
}
return (
  <div className="team" style={styling}></div>
);

4
模块未找到错误:错误原因为无法解析“/static/images/security-team.jpg”路径。 - Hassan Kandil

3

我正在使用Next.js v12.0.10,当我尝试像这样做时,它无法加载css背景图片:

<div style={{ backgroundImage: "url('/public/a.jpg')"}}>
</div>

但是当我在图像URL中省略/public时,一切正常:
<div style={{ backgroundImage: "url: '/a.jpg')"}}>
</div>

就像Ivan在上面说的那样:

public文件夹中的文件可以通过从基本URL(/)开始引用您的代码来引用。


太好了!这帮助我解决了我的问题。谢谢。 - undefined

3

您需要做的就是修改URL链接

background-image: url('/public/images/my-img.jpg'); 修改为 background-image: url('/static/images/my-img.jpg');


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接