Error: validateDOMNesting(…): <a> cannot appear as a descendant of <a>, Using AniLink inside AniLink

Error: validateDOMNesting(…): <a> cannot appear as a descendant of <a>, Using AniLink inside AniLink

我在 Gatsby 项目中使用此代码片段,似乎不允许在另一个 AniLink 中使用 AniLink,但我无法找出解决方案:

import React from 'react'
import AniLink from "gatsby-plugin-transition-link/AniLink";
const titleStyle = {
    fontWeight: "700",
}
const authorLinkStyle = {
    color: "#00BCD4"
}
const Author = ({ children, to }) => (
    <AniLink style={authorLinkStyle} to={to} className="font-weight-bold" fade>
        {children}
    </AniLink>
)
const Card = ({ title, description, timeStamp, authorName, slug }) => {
    const cardTextColor = typeof window !== "undefined" && getComputedStyle(document.documentElement).getPropertyValue("--card-text-color")
    const cardLinkStyle = { color: cardTextColor, textDecoration: "none" }
    return (
        <AniLink
            style={cardLinkStyle}
            to={slug}
            cover
            bg="#00BCD4"
        >
            <div className="card my-4" >
                <div className="card-body" >
                    <h5 className="card-title" style={titleStyle}>{title}</h5>
                    <p className="card-text">{description}</p>
                    <h6 className="card-subtitle text-muted">
                        <Author to="/about">{authorName}</Author> on {timeStamp}
                    </h6>
                </div>
            </div>
        </AniLink>)
}
export default Card

我认为错误发生在这一行:

<Author to="/about">{authorName}</Author> on {timeStamp}

F12错误:

有没有人在使用 AniLink 时看到这个错误? 任何建议都会很棒..

谢谢

嗯,基本上你发现了错误。您正在将一个组件(AniLink,它是一个锚点,<a>)包裹在另一个锚点(Author 组件)中。

这在编译并转换为输出 HTML 时正在创建一个无效的锚点结构作为另一个锚点 (<a><a>Link</a></a>) 的后代。不是 AniLink 的问题,也不是 React 或 Gatsby 的问题,而是组件结构的问题。

解决方法很简单,不要包裹。你可能想做这样的事情:

<div className="card my-4" >
    <div className="card-body" >
      <AniLink
          style={cardLinkStyle}
          to={slug}
          cover
          bg="#00BCD4"
        >
        <h5 className="card-title" style={titleStyle}>{title}</h5>
        <p className="card-text">{description}</p>
       </AniLink>
        <h6 className="card-subtitle text-muted">
            <Author to="/about">{authorName}</Author> on {timeStamp}
        </h6>
    </div>
</div>

上面的代码片段不会产生错误,但您可能需要调整布局以符合您的规范和设计。