【问题标题】:Problem with rendering markdown in NextJS/React在 NextJS/React 中渲染 markdown 的问题
【发布时间】:2021-11-07 08:02:25
【问题描述】:

我再次尝试在 NextJS/React 中呈现 markdown。由于某种原因,我的代码不起作用,这里是:

import ReactMarkdown from "react-markdown";
import gfm from 'remark-gfm';
const PostContent = () => {
    const source = `
        # Hello, world!
        ---
        ~this doesn't work.~
    `
    return (
        <ReactMarkdown remarkPlugins={[gfm]} children={source} />
    );
};

export default PostContent;

它不是渲染markdown,而是正常输出文本,就好像它是JSON:

谁能告诉我为什么会发生这种情况以及如何解决它?谢谢!

我无法提供更多细节,因为这是所有代码。

【问题讨论】:

    标签: reactjs next.js markdown react-markdown


    【解决方案1】:

    这似乎是一个空格问题,你太多了。

    这不起作用:

    const PostContent = () => {
        const source = `
            # Hello, world!
            ---
            ~this doesn't work.~
        `
        return (
            <ReactMarkdown remarkPlugins={[gfm]} children={source} />
        );
    };
    

    这行得通:

    const PostContent = () => {
      const source = `
    # Hello, world!
    ---
    ~this doesn't work.~
    `;
      return <ReactMarkdown remarkPlugins={[gfm]} children={source} />;
    };
    

    请注意,每行的“前导”空格已被删除

    【讨论】:

      【解决方案2】:

      您需要删除第一个空行和每行开头的所有空格。 它可能看起来很奇怪 - 但这是 ReactMarkdown 期望你做的。

      您的组件最终将如下所示:注意反引号文本中的“奇怪”间距。

      import ReactMarkdown from "react-markdown";
      import gfm from 'remark-gfm';
      
      const PostContent = () => {
      
          const source = `
      # Hello, world!
      ---
      ~this doesn't work.~
      `
          return (
              <ReactMarkdown remarkPlugins={[gfm]} children={source} />
          );
      };
      
      export default PostContent;
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-07
        • 2023-04-11
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-29
        相关资源
        最近更新 更多