如何在react hooks页面中的数据显示中添加代码片段的代码块

soc*_*way 0 javascript contentful react-hooks

我正在contentful我的 React Hooks 网站中显示博客内容。现在博客的完整描述已收到post.description。我想将code snippets, json datapost.description 中收到的内容显示为code block。还想将标题行添加到 h1 或 h2 标签。我们如何从描述字段中识别代码块?现在它只显示页面中的文本(请参阅添加的屏幕截图)

import React from "react";
import { Link, useParams } from "react-router-dom";
import MD from "react-markdown";
import { useSinglePost } from "../custom-hooks";
import Moment from 'moment';



export default function SinglePost() {
  const { id } = useParams();
  const [post, isLoading] = useSinglePost(id);

  const renderPost = () => {
    if (isLoading) return ( <div> <p className="noSearchData">Loading...</p> </div>);

    return (
      <React.Fragment>
        <div className="main_intro">
          <h3 className="blog_title">{post.title}</h3>
          <small className="blog_date">{Moment(post.createdAt).format('MMM DD YYYY')}</small>
          <pre className="blog_main_desc"><code>{post.description}</code></pre>
          <img
            className="blog_img"
            src={post.image.fields.file.url}
            alt={post.title}
          />
        </div>

        <div className="post__body">
          <MD source={post.body} />
        </div>
      </React.Fragment>
    );
  };

  return (
    <div className="post">
      <Link className="post__back" to="/">
        {"< Back"}
      </Link>

      {renderPost()}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

小智 5

要将代码片段作为代码块包含在 ReactJs 中,您可以使用语法荧光笔,例如react-syntax-highlighter

安装 npm react-syntax-highlighter --save

然后在您的代码中导入荧光笔:

import SyntaxHighLighter from 'react-syntax-highlighter';
import { dracula } from 'react-syntax-highlighter/dist/cjs/styles/hljs';

<SyntaxHighLighter language="javascript" style={dracula}>
{
    "class HelloMessage extends React.Component {\n render() {\n return ( \n <div>\nHello {this.props.name}\n</div>\n);\n }\n}\n\nReactDOM.render(\n<HelloMessage name='Taylor' />,\ndocument.getElementById('hello-example')\n);"
  }
</SyntaxHighLighter>
Run Code Online (Sandbox Code Playgroud)