使用场景
- 使用markdown编辑器编辑的内容
- 展示GPT中输出的内容(GPT输出格式是:markdown)
- 一些说明文档
其他说明
使用方法
// 安装的包说明
react-syntax-highlighter:15.5.0
react-markdown:8.0.7
// 按照命令
yarn add react-syntax-highlighter react-markdown
import React from 'react';
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { coyWithoutShadows, vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
const them = {
dark: vscDarkPlus,
light: coyWithoutShadows
};
interface IMarkdownRendererProps {
content: string;
darkMode?: boolean;
}
const MarkdownRenderer: React.FC<IMarkdownRendererProps> = ({ content, darkMode }) => {
const copyCode = function (value) {
navigator.clipboard.writeText(value);
};
const renderers = {
code: ({ node, inline, className, children, ...props }) => {
const languageMatch = /language-(\w+)/.exec(className || '');
const value = String(children).replace(/\n$/, '');
const lineNum = value.split('\n').length;
const toHtml = (codeContent, language?) => {
return (
<div style={{ position: 'relative' }}>
<div style={{ display: 'flex', position: 'absolute', top: 0, right: 0, padding: lineNum > 1 ? '10px' : '0 10px', color: '#999', zIndex: 1 }}>
<div style={{ padding: '0 5px' }}>{language}</div>
<div onClick={() => copyCode(value)} style={{ cursor: 'pointer', color: '#690' }}>
复制代码
</div>
</div>
{codeContent}
</div>
);
};
if (languageMatch) {
const language = languageMatch[1];
return toHtml(
<SyntaxHighlighter showLineNumbers={true} style={darkMode ? them.dark : them.light} language={language} PreTag='div' {...props}>
{value}
</SyntaxHighlighter>,
language
);
} else {
return toHtml(
<code className={className} {...props}>
{children}
</code>
);
}
}
};
return <ReactMarkdown components={renderers} children={content} />;
};
export default MarkdownRenderer;
const textContent = '# 标题\n```html\n<div>test</div>\n<div>test</div>\n```';
ReactDOM.render(<MarkdownRenderer content={textContent} />, document.getElementById('root'));
注意事项