react-codemirror2 实现mkdown
时间: 2023-06-26 21:03:28 浏览: 174
要实现 Markdown 编辑器,可以使用 React 和 react-codemirror2 库,这个库提供了一个 React 组件来集成 CodeMirror 编辑器。
首先,安装依赖:
```
npm install --save react-codemirror2 codemirror markdown-it
```
然后,在组件中引入需要的模块:
```js
import React, { useState } from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/theme/material.css';
import MarkdownIt from 'markdown-it';
```
在组件中,使用 useState 来管理 Markdown 源代码和渲染结果:
```js
const [value, setValue] = useState('');
const [result, setResult] = useState('');
```
然后,在 CodeMirror 组件中设置相关属性:
```js
<CodeMirror
value={value}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
options={{
mode: 'markdown',
theme: 'material',
lineNumbers: true,
}}
/>
```
在文本变化时,使用 MarkdownIt 库将源代码转换为 HTML:
```js
const md = new MarkdownIt();
const handleRender = () => {
setResult(md.render(value));
};
```
最后,将渲染结果显示在页面上:
```js
<div dangerouslySetInnerHTML={{ __html: result }} />
```
完整代码如下:
```js
import React, { useState } from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/markdown/markdown';
import 'codemirror/theme/material.css';
import MarkdownIt from 'markdown-it';
const MarkdownEditor = () => {
const [value, setValue] = useState('');
const [result, setResult] = useState('');
const md = new MarkdownIt();
const handleRender = () => {
setResult(md.render(value));
};
return (
<div>
<CodeMirror
value={value}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
options={{
mode: 'markdown',
theme: 'material',
lineNumbers: true,
}}
/>
<button onClick={handleRender}>Render</button>
<div dangerouslySetInnerHTML={{ __html: result }} />
</div>
);
};
export default MarkdownEditor;
```
阅读全文