将自定义 React 组件导入 GatsbyJS 中的 Markdown 中



在 GatsbyJS 中,在创作 markdown 文件时,如何导入和显示自定义 React 组件?

我正在使用官方的gatsby-starter-blog入门器,它带有降价支持。它非常适合博客文章。但是,我现在想将自定义 React 组件添加到我的降价文件中。我需要做什么才能实现这一目标?

这是我的尝试。没有错误,但自定义组件标签不会转换为实际的 React 组件。

1\index.md 后:

---
title: My first post
date: "2000-01-01"
description: Wouldn't it be sweet if there was a custom React component in here?
---
import CustomComponent from '../../../src/components/CustomComponent.js'
Lorem ipsum dolor.
<CustomComponent title="Test" />

文件夹结构:

content
- blog
-- post-1
---- index.md
src
- components
-- CustomComponent.js

Markdown 不支持 JSX。为此,您可以使用 MDX。Gatsby有大量的文档和官方插件来支持该功能。您可以在以下位置阅读更多信息: https://www.gatsbyjs.org/docs/mdx/

MDX 将允许您拥有如下所示的 MD 文件:

import { Chart } from '../components/chart'
The chart is rendered inside our MDX document.
<Chart />

你可以反过来在你的盖茨比应用程序中使用它,就像这样:

import React from "react"
import { MDXProvider } from "@mdx-js/react"
import { MDXRenderer } from "gatsby-plugin-mdx"
import mdxContent from "./your-content.mdx"
export default () => {
return (
<MDXProvider>
<MDXRenderer>{mdxContent}</MDXRenderer>
</MDXProvider>
)
}

最新更新