Gatsby链接在MDX呈现的页面上不使用isPartially Active

我一直在使用Gatsby和几个部分构建一个静态站点,我已经呈现了编写为MDX的页面,并通过它们自己的布局进行了解析。这都是通过Gatsby-plugin-mdx文件实现的,它工作得很好。

但是,我正在尝试让顶级导航在用户导航到该部分中的子页面时突出显示为活动的。我使用的是Gatsby文档中的代码,它在我创建的页面上像普通的JS文件一样工作。

示例:

<Link partiallyActive={true} activeClassName="header-nav-active" to={menu.url} title={menu.title}>
  {menu.label}
</Link>

它似乎不适用于MDX页面,即使在Location.pathname中呈现的内容是相同的。我目前的结构是:

src
-pages
--section
----section-subpage.js
--other section
----other-section-sub
-----index.mdx
----other-section-sub-2
-----index.mdx

最终,如果您查看此布局,我希望在您浏览该部分中的子页时将其突出显示为活动状态。


解决方案

您尝试过使用getProps helper function吗?因为Gatsby的路由器是从React(@reach/router)扩展而来的,所以您可以利用高级props来定制您的风格

您可以创建partiallyActive链接,如下所示:

const isPartiallyActive = ({ isPartiallyCurrent }) => {
  return isPartiallyCurrent
    ? { className: 'navlink-active navlink' }
    : { className: 'navlink' }
}

const PartialNavLink = props => (
  <Link getProps={isPartiallyActive} {...props}>
    {props.children}
  </Link>
)

然后只需使用:

 <PartialNavLink to="/figma">Figma</PartialNavLink>

或粗制滥造:

<Link getProps={({ isPartiallyCurrent }) => isPartiallyCurrent ? { className: "active" } : null } to={"/figma"}>
Figma
</Link>

相关文章