在 Gatsby 中,如何在 React 组件中显示 Markdown 文件的内容?
我用的是官方的gatsby-starter-blog Starter 附带 Markdown 支持。它非常适合已设置的博客文章。
但是,我现在添加了一个新的“关于”页面。在该页面上,我不想在 jsx 中编写所有内容,而是想在一个单独的 markdown 文件中编写一些内容,我可以将其导入到“关于”页面的 React 组件中。
我需要做什么才能实现这一目标?
文件夹结构:
content
- pages
-- about-content.md
src
- pages
-- about-page.js
PS:我不希望我的 md 文件变成它自己的页面。我想将它导入到 React 组件中。我希望该组件成为页面。
最佳答案
在gatsby-starter-blog
中,这是code snippet将 Markdown 文本转换为博客页面:
<section dangerouslySetInnerHTML={{ __html: post.html }} />
您将上面的 GraphQL 查询和代码片段放入 about-page.js
组件中:
const About = (props) => {
const { data: { legal: { edges } } } = props;
const { node: { childMarkdownRemark: { frontmatter, html } } } = edges[0];
return (
<Layout>
// display other React components
<section dangerouslySetInnerHTML={{ __html: html }} /> // display markdown
// display other React comonents
</Layout>
);
}
export const query = graphql`
{
legal: allFile(
filter: {
internal: {
mediaType: {eq: "text/markdown"}},
name: {eq: "about-content"}
edges {
node {
childMarkdownRemark {
html
}
}
}
}
}
`;
export default About;
请注意,Gatsby 会根据 pages
文件夹内的文件名隐式构建 URL。所以网址将是localhost:8000/about-page/
。
关于reactjs - 将 Markdown 文件导入到 Gatsby 中的 React 组件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61712050/