Notion Blog
技术分享1 分钟阅读

react实现markdown展示和语法高亮

安装 react-markdown 库实现markdown展示

npm install react-markdown

安装react-syntax-highlighter 实现语法高亮

npm install react-syntax-highlighter --save

代码示例

import ReactMarkdown from "react-markdown";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { dark } from "react-syntax-highlighter/dist/esm/styles/prism";


function Contents(props) {
let replacedText ="""对于包含代码块的字符串,可以使用以下方法将代码块展示出来:
```python
for code in code_blocks:
    print(code)
```
这是字符串文本, react怎么实现对代码语法高亮"""
return (
<ReactMarkdown
children={replacedText}
components={{
  code({ node, inline, className, children, ...props }) {
    const match = /language-(\w+)/.exec(className || "");
    return !inline && match ? (
      <SyntaxHighlighter
        children={String(children).replace(/\n$/, "")}
        style={dark}
        language={match[1]}
        PreTag="div"
        {...props}
      />
    ) : (
      <code className={className} {...props}>
        {children}
      </code>
    );
  },
}}
></ReactMarkdown>
)
}

有关使用上的问题,欢迎您在底部评论区留言,一起交流~

读者评论

评论会同步写入该文在 Notion 中的页面底部(与正文同页,便于管理)。

0/1500

暂无评论,欢迎抢沙发。