react-markdown集成remark-toc无效果,如何生成自动目录?
解决react-markdown中remark-toc不生成目录的问题
remark-toc插件默认需要在Markdown内容中添加触发标记才会生成目录,你的代码里缺少这个关键触发点,所以目录没有生成。
修复步骤
1. 在Markdown内容中添加触发标记
remark-toc默认识别[[toc]]作为生成目录的位置标记,把它放在你希望目录出现的地方(比如内容顶部):
const markdownContent = ` [[toc]] *{{ I expect to see an autogenerated headings-based table of contents above here. }}* # Using remark-toc with react-markdown ## Basic Markdown A paragraph with *emphasis* and **strong importance**. ## Strikethrough This ~is not~ strikethrough, but ~~this is~~! `;
2. 可选:自定义remark-toc配置
如果需要调整目录的触发标记、包含的标题层级等,可以给remark-toc传入配置参数,比如指定目录标题、限制标题深度:
remarkPlugins={[ [remarkGfm, { singleTilde: false }], [remarkToc, { heading: "目录", maxDepth: 2 }] // 自定义目录标题为“目录”,最多包含2级标题 ]}
完整修改后的代码
import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import remarkToc from "remark-toc"; export default function App() { const markdownContent = ` [[toc]] *{{ I expect to see an autogenerated headings-based table of contents above here. }}* # Using remark-toc with react-markdown ## Basic Markdown A paragraph with *emphasis* and **strong importance**. ## Strikethrough This ~is not~ strikethrough, but ~~this is~~! `; return ( <div className="App"> <ReactMarkdown children={markdownContent} remarkPlugins={[[remarkGfm, { singleTilde: false }], [remarkToc]]} /> </div> ); }
关键说明
remark-toc不会自动在内容顶部生成目录,它需要你在Markdown中明确指定生成位置——通过默认的[[toc]]或自定义触发标记,插件才会将该位置替换为基于文档标题的目录。
内容的提问来源于stack exchange,提问作者Bernard Hymmen
相关产品推荐
相关产品推荐

