【问题标题】:Gatsby Link not working with isPartially Active on MDX rendered pagesGatsby Link 在 MDX 渲染页面上无法使用 isPartially Active
【发布时间】:2022-02-04 13:54:42
【问题描述】:

我一直在用 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

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

【问题讨论】:

  • 你运行的是什么版本的 Gatsby?
  • 我正在使用 Gatsby v4

标签: javascript reactjs gatsby reach-router


【解决方案1】:

您是否尝试过使用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>

【讨论】:

  • 我已经调查过了,但盖茨比没有处理。我会试试这些样品,看看我会怎么做。谢谢
猜你喜欢
  • 2021-04-19
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2020-11-16
  • 2019-12-06
  • 1970-01-01
相关资源
最近更新 更多