react实现markdown
React 实现 Markdown 编辑器
使用 React 实现 Markdown 编辑器可以通过以下方法完成,结合现有库或自定义解析逻辑。
使用现成库(推荐)
安装 react-markdown 或 marked 等流行库:
npm install react-markdown
基本示例代码:
import React from 'react';
import ReactMarkdown from 'react-markdown';
function MarkdownEditor() {
const [markdown, setMarkdown] = React.useState('# Hello World');
return (
<div>
<textarea
value={markdown}
onChange={(e) => setMarkdown(e.target.value)}
/>
<ReactMarkdown>{markdown}</ReactMarkdown>
</div>
);
}
自定义解析逻辑
如果需要轻量级实现,可以编写简单的转换函数:
function parseMarkdown(text) {
return text
.replace(/^# (.*$)/gm, '<h1>$1</h1>')
.replace(/^## (.*$)/gm, '<h2>$1</h2>')
.replace(/`([^`]+)`/g, '<code>$1</code>');
}
function MarkdownPreview({ text }) {
const html = parseMarkdown(text);
return <div dangerouslySetInnerHTML={{ __html: html }} />;
}
添加语法高亮
结合 highlight.js 实现代码块高亮:
npm install highlight.js
使用示例:
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
function HighlightMarkdown({ children }) {
useEffect(() => {
hljs.highlightAll();
}, [children]);
return <ReactMarkdown>{children}</ReactMarkdown>;
}
支持扩展语法
通过 remark 插件生态系统支持表格、数学公式等:
npm install remark-gfm remark-math rehype-katex
配置示例:
import remarkGfm from 'remark-gfm';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[rehypeKatex]}
>
{markdownContent}
</ReactMarkdown>
注意事项
- 自定义解析时需注意 XSS 防护
- 大型文档考虑虚拟滚动优化性能
- 移动端需添加合适的输入体验优化
- 保存状态时建议同时存储原始 Markdown 和渲染结果
以上方案可根据项目需求组合使用,现成库适合快速开发,自定义解析适合特定需求场景。







