在Gatsby Markdown中使标题从h2开始

时间:2019-01-07 15:03:20

标签: markdown gatsby

我正在使用Gatsby构建基本的博客网站。我遇到了一个问题,就是我现有的博客帖子中使用#标题,但是我的Gatsby博客在页面顶部有一个h1。我希望Markdown中的#成为h2,##成为h3,等等...

有没有简单的方法可以实现这一目标? gatsby-transformer-remark似乎没有很多可用的选项,即使这样做,我仍在努力寻找适合我目的的remark-parse或remark-stringify选项。如果可以避免,我宁愿不编写自己的插件。

1 个答案:

答案 0 :(得分:1)

使用rehype-react模块可以做到这一点。在您的博客文章模板中,添加

import rehypeReact from 'rehype-react'

const renderAst = new rehypeReact({
  createElement: React.createElement,
  components: {
    h1: props => <h2>{props.children}</h2>,
    h2: props => <h3>{props.children}</h3>,
    // ...
  },
}).Compiler

并替换

<div dangerouslySetInnerHTML={{ __html: post.html }} />

使用

{
  renderAst(post.htmlAst)
}

,然后在您的graphql查询中将html更改为htmlAst

Here是有关使用remark&gatsby的更高级的示例。