reactjs - 将 Markdown 文件导入到 Gatsby 中的 React 组件中

标签 reactjs graphql gatsby

在 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/

相关文章:

javascript - react /Redux : separating presentational and container components dilemma.

environment-variables - Gatsby 如何使用环境变量?

deployment - 如何使 S3 Cloudfront 上部署的 Gatsby 网站上的服务 worker 缓存失效?

reactjs - 如何将任意字符串 HTML 内容注入(inject)到我的 gatsbyjs 网站的头部?

javascript - react : update component after an async event not connect to the component

reactjs - 使用 react.js 和 promise 解析错误 : Unexpected token, 预期为 ","

javascript - 使用 2017 年的 React-router React-transition-group 示例,其中内容组件不渲染

graphql - 日期之间的 Hasura graphql 查询

wordpress - 如何在 Gatsby 中获取所有 WordPress 帖子并显示标签

strongloop - 如何将 Relay/GraphQL 与 Loopback 一起使用?