为什么我的目录组件每次单击其中一个链接时都会在其链接中添加"{"-" + 1}"?



按照本教程,我在我的站点中实现了一个目录组件。

它可以工作,但是每次我单击TOC的一个链接时,TOC中的所有链接(包括单击的链接)都会附加{"-" + 1}。所以如果我点击一个链接,所有的链接都从#first-heading,#second-heading等等转到#first-heading-1,#second-heading-1等等。如果我再次点击其中一个链接,它们都会得到#first-heading-2,#second-heading-2等等。这种行为当然是有问题的,因为它破坏了链接。

是什么引起的?我怎么修理它?

我注意到教程使用remark-slug插件的标题,而我使用gatsby-autolink-headers插件。这是问题的根源吗?我无法测试前者,因为我在试图安装它时出现错误。

编辑:我试过两个插件。同样的问题。

TableOfContents.js

import React from "react"
import Slugger from "github-slugger"
import { Link } from "gatsby"
const slugger = new Slugger()
export default ({ headings }) => (
<div className="table-of-contents">
<h3>On this page</h3>
<ol>
{headings
.filter(heading => heading.depth !== 1)
.map(heading => (
<li key={heading.value}>
<Link
to={"#" + slugger.slug(heading.value)}
>
{heading.value}
</Link>
</li>
))}
</ol>
</div>
)

post-template.js

import * as React from "react"
import { graphql } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import Layout from "../components/layout.js"
import Seo from "../components/seo.js"
const PostTemplate = ({ data, location }) => {
let post = data.mdx
return (
<Layout location={location}>
<Seo
title={post.frontmatter.title}
description={post.frontmatter.lead}
date={post.frontmatter.computerDate}
/>
<article className="article">
<h1 itemprop="headline">{post.frontmatter.title}</h1>
<p
className="lead"
itemprop="introduction"
>
{post.frontmatter.lead}
</p>
<MDXRenderer headings={post.headings}>
{post.body}
</MDXRenderer>
</article>
</Layout>
)
}
export default PostTemplate
export const pageQuery = graphql`
query PostBySlug($id: String!) {
site {
siteMetadata {
title
}
}
mdx(id: {eq: $id}) {
id
excerpt(pruneLength: 160)
body
frontmatter {
title
computerDate: date(formatString: "YYYY-MM-DD")
humanDate: date(formatString: "DD MMMM YYYY")
lead
}
headings {
depth
value
}
}
}
`

index.mdx

---
/* frontmatter */
---
<!-- component imported as shortcode in `layout.js` -->
<TableOfContents headings={props.headings} />

layout.js(节选)

import TableOfContents from "./article-components/TableOfContents"
const shortcodes = {
TableOfContents
}
export default function Layout({ children }) {
return (
<div className="layout-wrapper">
<Header />
<main>
<MDXProvider components={shortcodes}>
{children}
</MDXProvider>
</main>
</div>
)
}

这是因为slugger。在他们的文档中:

slugger.slug('foo')
// returns 'foo'
slugger.slug('foo')
// returns 'foo-1'
slugger.slug('bar')
// returns 'bar'
slugger.slug('foo')
// returns 'foo-2'

因为它确保链接是唯一的(像GitHub一样),它附加了-1,-2等。

只要你使用你的gatsby-autolink-headers插件可以摆脱slugger的实现。如果需要,您可以使用正常的链接值(heading.value)、slug字段(如果提供的话),或者使用自定义函数对其进行清理,例如:

function slugify (text) {
return text
.toString()
.toLowerCase()
.normalize(`NFD`)
.trim()
.replace(/s+/g, `-`)
.replace(/[^w-]+/g, ``)
.replace(/--+/g, `-`);
};
<Link to={"#" + slugify(heading.value)}>