如何从 Next.js 中的 next/image 中删除包装器跨度?

Jen*_*er 16 reactjs next.js nextjs-image

我正在倾斜 Next.js,我发现它用两个跨度next/image包装img并将内联样式添加到img覆盖我的类样式的标签中

如何删除内联样式和包装 HTML 标签(如spans和 )divs

我的代码看起来像

import Image from 'next/image';
<Image className={'imgBack'} src={myImg} width="160" height="160" alt="" />
Run Code Online (Sandbox Code Playgroud)

结果

<span style="box-sizing: border-box; display: inline-block; overflow: hidden; width: initial; height: initial; background: none; opacity: 1; border: 0px; margin: 0px; padding: 0px; position: relative; max-width: 100%;">
    <span style="box-sizing: border-box; display: inline-block; overflow: hidden; width: initial; height: initial; background: none; opacity: 1; border: 0px; margin: 0px; padding: 0px; position: relative; max-width: 100%;">
    <img alt="" src="/_next/image?url=%sq=75" decoding="async" data-nimg="intrinsic" class="imgBack" style="position: absolute; inset: 0px; box-sizing: border-box; padding: 0px; border: none; margin: auto; display: block; width: 0px; height: 0px; min-width: 100%; max-width: 100%; min-height: 100%; max-height: 100%;" srcset="/_next/image?url=%2F_next%s;q=75 1x, /_next/image?url=%2F_next%s;q=75 2x">
    </span>
<span>
Run Code Online (Sandbox Code Playgroud)

预期结果

<img src="./myImg" class="imgBack" alt="" width="160" height="160" />
Run Code Online (Sandbox Code Playgroud)

我已阅读该next/image文档,但找不到解决该问题的方法。

jul*_*ves 15

使用next/future/image

注意:在 Next.js 13 中,next/future/image已转换为next/image,以上不再是问题。

从 Next.js 12.3 开始,您可以使用新组件,默认情况下next/future/image它会渲染单个<img>元素,而无需任何附加元素<div>或包装器。<span>

请注意,在 Next.js 12.2.x 中,该next/future/image组件仍处于实验阶段,需要在next.config.js.

module.exports = {
    experimental: {
        images: {
            allowFutureImage: true
        }
    },
    // Rest of the config
}
Run Code Online (Sandbox Code Playgroud)

next/image与使用layout="raw"

在版本 12.2.0 之前和从 12.1.1 开始,可以使用实验layout="raw"模式在没有包装器或样式的情况下渲染图像。

要启用原始布局模式,请将以下内容添加到您的next.config.js

module.exports = {
    experimental: {
        images: {
            layoutRaw: true
        }
    },
    // Rest of the config
};
Run Code Online (Sandbox Code Playgroud)

layout="raw"然后在组件中使用Image

<Image 
    className="imgBack" 
    src={myImg} 
    width="160" 
    height="160" 
    alt="" 
    layout="raw" 
/>
Run Code Online (Sandbox Code Playgroud)


小智 0

从 nextjs-11 迁移到 nextjs-12 时遇到类似的问题。Nextjs 12 使用span而不是div,因此只需更新您的 CSS 文件

.myImg > span {
//Your CSS 
}
Run Code Online (Sandbox Code Playgroud)

  • 仅仅改变 CSS 是不够的。这些跨度带有内置的内联样式。由于这个原因,在 CSS 中按标签名称选择不起作用。(在寻找摆脱跨度的方法之前我尝试过) (3认同)