首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MDX渲染器- Gatsby Site - <li>、<pre>和<code>标记不渲染

MDX渲染器- Gatsby Site - <li>、<pre>和<code>标记不渲染
EN

Stack Overflow用户
提问于 2021-01-31 22:52:53
回答 1查看 470关注 0票数 1

我正在尝试弄清楚为什么我必须在gatsby-browser.js中指定所有的HTML标记,以便MDXrenderer能够理解如何对这些HTML标记设置样式。

内容通过GraphQL查询来自GraphCMS。

我一直在研究其他gatsby项目,这些项目没有设置规范,但它们正确地呈现了HTML标记。

我可以针对大多数HTML标记,但我不知道"ul“和"li”标记是如何呈现的。例如,我可以针对它们并应用颜色,但在查看时,它仍然看起来像页面上的"p“标签。不过,如果您检查该元素,它确实会显示"ul“和"li”标记。

如下例所示:

Webpage with inspection

下面是我的gatsby-node.js文件:

代码语言:javascript
复制
const path = require("path")

exports.createPages = async ({ actions: { createPage }, graphql }) => {
  const { data } = await graphql(
    `
      {
        pages: allGraphCmsPage {
          nodes {
            id
            content {
              markdownNode {
                childMdx {
                  body
                }
              }
            }
            seo {
              description
              image {
                url
              }
              keywords
              title
            }
            slug
            subtitle
            title
          }
        }
        posts: allGraphCmsPost(sort: { fields: date, order: ASC }) {
          edges {
            nextPost: next {
              slug
              title
            }
            page: node {
              id
              author {
                id
                name
                title
              }
              content {
                markdownNode {
                  childMdx {
                    body
                  }
                }
              }
              date: formattedDate
              excerpt
              seo {
                description
                image {
                  url
                }
                keywords
                title
              }
              slug
              title
            }
            previousPost: previous {
              slug
              title
            }
          }
        }
      }
    `
  )

  if (data.errors) throw data.errors

  data.posts.edges.forEach(({ nextPost, page, previousPost }) => {
    createPage({
      component: path.resolve("./src/templates/article-post.tsx"),
      context: {
        id: page.id,
        page,
        previousPost,
        nextPost,
      },
      path: `/articles/${page.slug}`,
    })
  })

  data.pages.nodes.forEach(page => {
    createPage({
      component: path.resolve("./src/templates/default-page.tsx"),
      context: {
        page,
      },
      path: `/${page.slug}`,
    })
  })
}

exports.createResolvers = ({ createResolvers }) => {
  const resolvers = {
    GraphCMS_Post: {
      formattedDate: {
        type: "String",
        resolve: source => {
          const date = new Date(source.date)

          return new Intl.DateTimeFormat("en-US", {
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "numeric",
          }).format(date)
        },
      },
    },
  }

  createResolvers(resolvers)
}

下面是我的gatsby-config.js文件:

代码语言:javascript
复制
require("dotenv").config()

const path = require("path")

module.exports = {
  siteMetadata: {
    title: `Code Shape`,
    description: `Learn to create great things.`,
    author: `@codeshape`,
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/static/images/icons`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/static/images/logos`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/static/images/profiles`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `posts`,
        path: `${__dirname}/src/posts/`,
      },
    },
    {
      resolve: "gatsby-plugin-page-creator",
      options: {
        path: `${__dirname}/src/posts`,
      },
    },
    `gatsby-plugin-mdx`,
    {
      resolve: "gatsby-source-graphcms",
      options: {
        endpoint: process.env.GRAPHCMS_ENDPOINT,
        token: process.env.GRAPHCMS_TOKEN,
        buildMarkdownNodes: true,
        downloadLocalImages: true,
      },
    },
    `gatsby-plugin-styled-components`,
    `gatsby-plugin-react-helmet`,
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
  ],
}

下面是我的gatsby-browser.js文件:

代码语言:javascript
复制
import React from "react"
import { MDXProvider } from "@mdx-js/react"
import Layout from "./src/components/layout/layout"

/* eslint-disable */
const components = {
  wrapper: ({ children }) => <>{children}</>,
  h1: props => (
    <h1 style={{ fontSize: "60px", fontWeight: "bold" }} {...props} />
  ),
  h2: props => (
    <h2 style={{ fontSize: "40px", fontWeight: "bold" }} {...props} />
  ),
  h3: props => (
    <h3 style={{ fontSize: "30px", fontWeight: "bold" }} {...props} />
  ),
  h4: props => (
    <h4 style={{ fontSize: "20px", fontWeight: "bold" }} {...props} />
  ),
  p: props => <p style={{ fontSize: "16px", lineHeight: 1.6 }} {...props} />,
  strong: props => (
    <strong style={{ fontWeight: "900", lineHeight: 1.6 }} {...props} />
  ),
  img: props => <img style={{ width: "100%" }} {...props} />,
  pre: props => {
    const className = props.children.props.className || ""
    const matches = className.match(/language-(?<lang>.*)/)
    return (
      <Highlight
        {...defaultProps}
        code={props.children.props.children}
        language={
          matches && matches.groups && matches.groups.lang
            ? matches.groups.lang
            : ""
        }
      >
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className} style={style}>
            {tokens.map((line, i) => (
              <div {...getLineProps({ line, key: i })}>
                {line.map((token, key) => (
                  <span {...getTokenProps({ token, key })} />
                ))}
              </div>
            ))}
          </pre>
        )}
      </Highlight>
    )
  },
}

const wrapPageElement = ({ element, props }) => (
  <Layout {...props}>{element}</Layout>
)

const wrapRootElement = ({ element }) => (
  <MDXProvider components={components}>{element}</MDXProvider>
)

export { wrapPageElement, wrapRootElement }

这里是我的文章的模板-post.tsx文件:

代码语言:javascript
复制
import React from "react"
import { graphql, Link } from "gatsby"
import Img from "gatsby-image"
import { MDXRenderer } from "gatsby-plugin-mdx"
import styled from "styled-components"
import {
  BodyMain,
  Caption,
  H1,
  MediumText,
} from "../components/styles/TextStyles"
import ReactDisqusComments from "react-disqus-comments"
import LazyLoad from "react-lazy-load"

export const pageQuery = graphql`
  fragment AssetFields on GraphCMS_Asset {
    id
    localFile {
      childImageSharp {
        fluid(maxWidth: 600) {
          ...GatsbyImageSharpFluid
        }
      }
    }
  }

  query ArticlePostQuery($id: String!) {
    authorImage: graphCmsAsset(
      authorAvatar: {
        elemMatch: { posts: { elemMatch: { id: { in: [$id] } } } }
      }
    ) {
      ...AssetFields
    }
    coverImage: graphCmsAsset(
      coverImagePost: { elemMatch: { id: { eq: $id } } }
    ) {
      ...AssetFields
    }
  }
`

export default function ArticlePostTemplate({
  data: { authorImage, coverImage },
  pageContext: { nextPost, page, previousPost },
}) {
  return (
    <Wrapper>
      <Header>
        <PublishDate>{page.date}</PublishDate>
        <PageTitle>{page.title}</PageTitle>
      </Header>
      <InformationWrapper>
        <AuthorWrapper>
          <AuthorAvatar>
            <Img
              fluid={authorImage.localFile.childImageSharp.fluid}
              fadeIn={false}
              className="Image"
            />
          </AuthorAvatar>
          <AuthorTextWrapper>
            <AuthorName>{page.author.name}</AuthorName>
            <AuthorTitle>{page.author.title}</AuthorTitle>
          </AuthorTextWrapper>
        </AuthorWrapper>
      </InformationWrapper>
      <ContentWrapper>
        <Img
          fluid={coverImage.localFile.childImageSharp.fluid}
          fadeIn={false}
          className="CoverImage"
        />
        <MDXRenderer>{page.content.markdownNode.childMdx.body}</MDXRenderer>
      </ContentWrapper>
      <Navigation>
        {(nextPost || previousPost) && (
          <div>
            <hr className="Divider" />
            {nextPost && (
              <div>
                <h2>Next Post</h2>
                <div>
                  <Link to={`/articles/${nextPost.slug}`}>
                    {nextPost.title}
                  </Link>
                </div>
                <hr className="Divider" />
              </div>
            )}
            {previousPost && (
              <div>
                <h2>Previous Post</h2>
                <div>
                  <Link to={`/articles/${previousPost.slug}`}>
                    {previousPost.title}
                  </Link>
                </div>
                <hr className="Divider" />
              </div>
            )}
          </div>
        )}
        <div>
          <Link to="/articles/" className="">
            &larr; Back to the blog
          </Link>
        </div>
      </Navigation>
      <LazyLoad offsetTop={400}>
        <ReactDisqusComments
          shortname="codeshape"
          identifier={page.id}
          title={page.title}
          url={page.url}
          category_id={page.category_id}
        />
      </LazyLoad>
    </Wrapper>
  )
}

const Wrapper = styled.div`
  margin: 1.875rem;
  display: grid;
  grid-gap: 1.875rem;
`

const Header = styled.div`
  text-align: center;
  margin: 0 auto;
`

const PublishDate = styled(BodyMain)`
  color: #757372;
`

const PageTitle = styled(H1)``

const InformationWrapper = styled.div`
  display: grid;
  align-items: center;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
`

const ContentWrapper = styled.div`
  display: grid;
  grid-gap: 1rem;
  margin: 0 auto;
  max-width: 80rem;

  .CoverImage {
    border-radius: 1.25rem;
    object-fit: cover;
  }
`

const AuthorWrapper = styled.div`
  margin: 0 auto;
  padding: 1rem;
  display: grid;
  grid-gap: 1rem;
  grid-template-columns: auto auto;
  width: 20rem;
  justify-content: center;
  align-content: center;
`

const AuthorAvatar = styled.div`
  .Image {
    border-radius: 50%;
    border: 3px solid white;
    width: 4rem;
  }
`

const AuthorTextWrapper = styled.div`
  display: grid;
  justify-content: center;
  align-content: center;
`

const AuthorName = styled(MediumText)`
  font-weight: 900;
`

const AuthorTitle = styled(Caption)`
  color: #757372;
`

const Navigation = styled.div`
  margin: 0 auto;
  text-align: center;
  padding: 1.875rem;
  display: grid;
  grid-gap: 1rem;
  width: 18rem;

  .Divider {
    color: #757372;
    line-height: 3rem;
  }
`

package.json文件中的依赖项:

代码语言:javascript
复制
    "@mdx-js/mdx": "^1.6.22",
    "@mdx-js/react": "^1.6.22",
    "@types/react-helmet": "^6.1.0",
    "@types/styled-components": "^5.1.4",
    "autoprefixer": "^10.2.3",
    "babel-plugin-styled-components": "^1.12.0",
    "gatsby": "^2.28.0",
    "gatsby-image": "^2.10.0",
    "gatsby-plugin-manifest": "^2.8.0",
    "gatsby-plugin-mdx": "^1.9.0",
    "gatsby-plugin-offline": "^3.6.0",
    "gatsby-plugin-react-helmet": "^3.6.0",
    "gatsby-plugin-sharp": "^2.13.4",
    "gatsby-plugin-styled-components": "^3.9.0",
    "gatsby-source-filesystem": "^2.7.0",
    "gatsby-source-graphcms": "^2.2.0",
    "gatsby-transformer-sharp": "^2.11.0",
    "prop-types": "^15.7.2",
    "react": "^16.14.0",
    "react-disqus-comments": "^1.4.0",
    "react-dom": "^16.14.0",
    "react-helmet": "^6.1.0",
    "react-lazy-load": "^3.1.13",
    "styled-components": "^5.2.1"
  },

为了让MDXrenderer正常工作,你能帮我做些什么吗?我仍然需要弄清楚列表和代码块是如何呈现的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-31 23:35:18

你完全夸大了这个问题。你不需要在gatsby-browser.js中创建一个实例来“让MDX理解”。自从你渲染一个<ul><li>之后,你的MDX就可以正常工作了。您只是缺少样式。

在截图中,你已经分享了,可以看到以下内容:

代码语言:javascript
复制
Inherited from ul
ol, ul {
   list-style: none;
}

这会让你的列表“看起来像<p>”。

你只需要给它们添加正确的样式或者删除重置的样式。默认情况下,<ul>具有:

代码语言:javascript
复制
display: block; 
list-style-type: disc; 
margin-top: 1em; 
margin-bottom: 1 em; 
margin-left: 0; 
margin-right: 0; 
padding-left: 40px;

<li>

代码语言:javascript
复制
display: list-item; 

一旦你恢复了默认的样式,你的列表标签看起来就会像原来一样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65980498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档