【问题标题】:Strapi Rich text content not showing correctly on Web PageStrapi 富文本内容未在网页上正确显示
【发布时间】:2021-08-31 20:38:01
【问题描述】:

我目前使用 Strapi 作为我的 CMS,并使用 NextJs/React 作为我的前端。我在我的strapi 中包含了 1 个字段作为内容丰富的字段。当我在 Strapi 本身中添加我的内容并查看预览时,它会显示正确的输出以及所有间距和下划线等。但是当我切换到网页视图时,这一切都是 1 个没有任何样式的句子。我添加下划线的地方在我的网页中显示为<u>Sentence</u>

这是我当前的代码:

export default function name({ posts }) {
  return (
    <>
      <div>
        <div>
          {posts.Title}
        </div>
      </div>
      <div>
        {posts.Content}
      </div>

      <Carousel />
    </>
  );
}

// Tell nextjs how many pages are there
export async function getStaticPaths() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  const paths = posts.map((blog) => ({
    params: { id: blog.id.toString() },
  }));

  return {
    paths,
    fallback: false,
  };
}

// Get data for each individual page
export async function getStaticProps({ params }) {
  const { id } = params;

  const res = await fetch(`http://localhost:1337/blogs?id=${id}`);
  const data = await res.json();
  const posts = data[0];

  return {
    props: { posts },
  };
}

网页预览:

导入 react-markdown 时出现以下错误

【问题讨论】:

    标签: reactjs next.js strapi


    【解决方案1】:

    这是因为您必须将 markdown 转换为 HTML。您可以在本教程中找到一个示例:https://strapi.io/blog/build-a-blog-with-next-react-js-strapi

    首先,安装“react-markdown”:

    npm install react-markdown
    # or
    yarn add react-markdown
    

    下面的代码应该可以工作:

    import ReactMarkdown from "react-markdown";
    // ...
    
    export default function name({ posts }) {
      return (
        <>
          <div>
            <div>
              {posts.Title}
            </div>
          </div>
          <div>
              <ReactMarkdown source={posts.Content} escapeHtml={false} />
          </div>
    
          <Carousel />
        </>
      );
    }
    
    // Tell nextjs how many pages are there
    export async function getStaticPaths() {
      const res = await fetch("http://localhost:1337/blogs");
      const posts = await res.json();
    
      const paths = posts.map((blog) => ({
        params: { id: blog.id.toString() },
      }));
    
      return {
        paths,
        fallback: false,
      };
    }
    
    // Get data for each individual page
    export async function getStaticProps({ params }) {
      const { id } = params;
    
      const res = await fetch(`http://localhost:1337/blogs?id=${id}`);
      const data = await res.json();
      const posts = data[0];
    
      return {
        props: { posts },
      };
    }
    

    顺便说一句,要在 Strapi 中只检索一个条目,您应该使用单一条目 API 端点:https://strapi.io/documentation/developer-docs/latest/developer-resources/content-api/content-api.html#get-an-entry

    【讨论】:

    • 我在尝试此操作时遇到错误。我在帖子中包含了错误的屏幕截图
    猜你喜欢
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2020-10-18
    • 1970-01-01
    • 2020-02-08
    相关资源
    最近更新 更多