Has*_*dil 9 html css reactjs next.js
问题只是我试图访问静态图像以在 React 的内联 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 (
<dev className="team" style={styling}>
</dev>
);
Run Code Online (Sandbox Code Playgroud)
}
这是 console.log 结果:
/_next/static/images/security-team-449919af8999ae47eaf307dca4dda8e1.jpg
图像没有出现,然后没有发生错误,我尝试在浏览器中输入 website-url + console.log 结果图像出现了!
M.I*_*lam 110
首先导入图片文件
import bg from '../../assets/images/security-team.jpg'
Run Code Online (Sandbox Code Playgroud)
然后应用内联样式
style={{
backgroundImage: `url(${bg.src})`,
width: '100%',
height: '100%',
}}
Run Code Online (Sandbox Code Playgroud)
Pet*_*r W 55
我将next@11.0图像放在公共文件夹中,然后在样式文件中使用以下内容并且它有效。
background-image: url('/image.svg');
Run Code Online (Sandbox Code Playgroud)
jfu*_*unk 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>
Run Code Online (Sandbox Code Playgroud)
thp*_*hpo 12
包 next-images 对我有用。
第一的 :
yarn add next-images
Run Code Online (Sandbox Code Playgroud)
然后,在 next.config.js 文件中:
const withImages = require('next-images')
module.exports = withImages()
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
<div
style={{
backgroundImage: "url(" + `${require("./path-to-the-image")}` + ")",
width: "100%",
height:[HEIGHT OF THE IMAGE],
backgroundRepeat: "no-repeat",
backgroundSize: "cover"
}}
>XXX</div>
Run Code Online (Sandbox Code Playgroud)
有关下一个图像的更多信息:https : //github.com/twopluszero/next-images
小智 10
正如nextjs文档所述(https://nextjs.org/docs/basic-features/static-file-serving):
publicNext.js 可以在根目录中调用的文件夹下提供静态文件,例如图像 。
public然后,您的代码可以从基本 URL ( ) 开始引用其中的文件/。
所以从文件夹中引用我们的图像的正确方法是public:
CSS 示例:
background-image: url('/your-image.jpg');
Run Code Online (Sandbox Code Playgroud)
JSX 示例:
import Image from 'next/image'
<Image src="/your-image.jpg" alt="Image description" width="64" height="64" />
Run Code Online (Sandbox Code Playgroud)
样式/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;
}
Run Code Online (Sandbox Code Playgroud)
当我使用 JSX 样式然后添加位置绝对属性时,它工作得很好。
像这样:
<style JSX>{`
.team {
width:100%;
height:100%;
position:absolute;
background: url('`+img+`') no-repeat;
}
`}</style>
Run Code Online (Sandbox Code Playgroud)