【问题标题】:Gatsby: img is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`Gatsby:img 是一个空元素标签,不能有 `children` 也不能使用 `dangerouslySetInnerHTML`
【发布时间】:2019-07-17 10:21:11
【问题描述】:

我正在尝试使用 Gatsby Js 构建一个包含已导入图像的组件。但是,当使用锚 HTML 标记添加链接时,我会收到 img is a void element tag and must neither havechildrennor usedangerouslySetInnerHTML`。

没有<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 链接添加到图像的正确方法是什么?

【问题讨论】:

  • 正如错误/警告所说。这是&lt;img /&gt; 不是&lt;img&gt;&lt;/img&gt;
  • 嗨@Andreas - 我试过` medium.com"> `并收到同样的错误

标签: javascript html reactjs gatsby


【解决方案1】:

您应该能够将图像导入组件中,然后像这样将其添加到图像 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

但是,如果您在开始和结束&lt;img&gt; 标记之间放置任何内容(甚至只是一个空格),gatsby 似乎认为它有子元素并且无法正确编译。

【讨论】:

  • 谢谢。它是标签之间的空格字符!
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2021-04-01
  • 2020-08-14
  • 1970-01-01
  • 2020-03-05
  • 1970-01-01
  • 2021-04-08
相关资源
最近更新 更多