React 的 Markdown 渲染
2024年2月21日 12:11
项目需求中有一个功能是支持 Markdown 渲染,尽量仿照 ChatGPT、Claude 的效果。
该文章的目的是记录我在实现这个功能时遇到的问题和解决方案。
react-markdown
先安装 react-markdown。
npm install react-markdown此处运用 react-markdown 库的官方示例中的文本来进行测试:
# A demo of `react-markdown``react-markdown` is a markdown component for React.👉 Changes are re-rendered as you type.👈 Try writing some markdown on the left.## Overview* Follows [CommonMark](https://commonmark.org)* Optionally follows [GitHub Flavored Markdown](https://github.github.com/gfm/)* Renders actual React elements instead of using `dangerouslySetInnerHTML`* Lets you define your own components (to render `MyHeading` instead of `'h1'`)* Has a lot of plugins## ContentsHere is an example of a plugin in action([`remark-toc`](https://github.com/remarkjs/remark-toc)).**This section is replaced by an actual table of contents**.## Syntax highlightingHere is an example of a plugin to highlight code:[`rehype-highlight`](https://github.com/rehypejs/rehype-highlight).```jsimport React from 'react'import ReactDOM from 'react-dom'import Markdown from 'react-markdown'import rehypeHighlight from 'rehype-highlight'const markdown = `# Your markdown here`ReactDOM.render( <Markdown rehypePlugins={[rehypeHighlight]}>{markdown}</Markdown>, document.querySelector('#content'))\```> Pretty neat, eh?## GitHub flavored markdown (GFM)For GFM, you can *also* use a plugin:[`remark-gfm`](https://github.com/remarkjs/react-markdown#use).It adds support for GitHub-specif...剩余内容已隐藏
查看完整文章以阅读更多