javascript - Gatsby: img 是一个空元素标签,不能有 `children` 也不能使用 `dangerouslySetInnerHTML`

标签 javascript html reactjs gatsby

我正在尝试使用 Gatsby Js 构建一个包含导入图像的组件。但是,当添加带有 anchor HTML 标记的链接时,我收到了 img is a void element tag and must neither have child nor use dangerouslySetInnerHTML`。

没有<a> ... </a>没有这样的错误。

我的代码:

import React from "react"
import medium from "../images/medium.png"


const Socials = () => (
    <div>
        <a href="https://medium.com"> <img src={medium}> </img> </a>
    </div>
)
export default Socials

堆栈跟踪:

  in img (at Socials.js:8)
    in a (at Socials.js:8)
    in div (at Socials.js:7)
    in Socials (at pages/index.js:44)
    in IndexPage (created by HotExportedIndexPage)
    in AppContainer (created by HotExportedIndexPage)
    in HotExportedIndexPage (created by PageRenderer)
    in PageRenderer (created by JSONStore)
    in JSONStore (created by RouteHandler)
    in RouteHandler (created by EnsureResources)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (created by EnsureResources)
    in ScrollContext (created by EnsureResources)
    in RouteUpdates (created by EnsureResources)
    in EnsureResources (created by LocationHandler)
    in LocationHandler (created by LocationProvider)
    in LocationProvider (created by Context.Consumer)
    in Location (created by Root)
    in Root
    in _default

将 URL 链接添加到图像的正确方法是什么?

最佳答案

您应该能够将图像导入您的组件,并像这样将其添加到图像 src。

import React from "react"
import gatsbyIconImage from "../images/gatsby-icon.png"

const IndexPage = () => (
  <>
    <a href="https://stackoverflow.com"><img alt="stack overflow" src={gatsbyIconImage}></img></a>
  </>
)

export default IndexPage

但是,如果您在开头和结尾之间放置任何内容 <img>标签(即使只是一个空格), Gatsby 似乎认为它有子元素并且不会正确编译。

关于javascript - Gatsby: img 是一个空元素标签,不能有 `children` 也不能使用 `dangerouslySetInnerHTML`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57073650/

相关文章:

javascript - jQuery Mobile 页面之外的持久性 HTML

javascript - 文本仍然包裹在它的父 div 中 - CSS,React

javascript - Redux 推送到嵌套数组而不改变状态

javascript - gulp 通知依赖于任务完成而无需 .pipe

javascript - jQuery UI 的高亮效果可以应用于表单文本输入吗?

javascript - Stripe checkout 在 Angular 1.x 中不起作用

html - 使用 HTML 和 CSS 创建的网页上的额外空间

javascript - 如何在 Worker 中预加载图像?

javascript window.open 并添加参数

javascript - react 数据网格自定义行格式化程序