react-markdown-editor-lite组件使用

react-markdown-editor-lite组件使用

_

react-markdown-editor-lite 是一个功能强大的React Markdown编辑器,提供了丰富的功能和灵活的配置选项。它支持Markdown的基本语法、高级语法以及自定义扩展。以下是该组件的功能简介和大部分语法示例:

GitHub:组件API配置项编辑时的组件控制

功能简介

  1. 实时预览

  • 支持Markdown内容的实时预览,所见即所得。

  1. 自定义渲染

  • 可以自定义Markdown解析器和渲染器,例如使用markdown-it

  1. 插件系统

  • 支持插件扩展,可以添加自定义按钮和功能。

  1. 主题支持

  • 支持自定义主题,可以根据需求调整编辑器的外观。

  1. 事件处理

  • 提供丰富的事件处理机制,例如内容变化、光标位置变化等。

基本使用示例

import React from 'react';
import MdEditor from 'react-markdown-editor-lite';
import MarkdownIt from 'markdown-it';
import 'react-markdown-editor-lite/lib/index.css';

// 初始化Markdown解析器
const mdParser = new MarkdownIt();

function App() {
  const handleEditorChange = ({ html, text }) => {
    console.log('handleEditorChange', html, text);
  };

  return (
    <div className="App">
      <MdEditor
        value=""
        style={{ height: '500px' }}
        renderHTML={(text) => mdParser.render(text)}
        onChange={handleEditorChange}
      />
    </div>

  );
}

export default App;

支持的Markdown语法

标题

# 一级标题
## 二级标题
### 三级标题

强调

*斜体* 或 _斜体_
**粗体** 或 __粗体__
~~删除线~~

列表

- 无序列表项
- 无序列表项

1. 有序列表项
2. 有序列表项

链接

[链接文本](https://example.com)

图片

![替代文本](https://example.com/image.jpg)

引用

> 这是一个引用

代码

`单行代码`

多行代码块

表格

| 头部1 | 头部2 |
| ----- | ----- |
| 单元格1 | 单元格2 |
| 单元格3 | 单元格4 |

自定义插件示例

你可以通过插件系统扩展编辑器的功能。以下是一个简单的自定义按钮插件示例:

import React from 'react';
import MdEditor from 'react-markdown-editor-lite';
import MarkdownIt from 'markdown-it';
import 'react-markdown-editor-lite/lib/index.css';

// 初始化Markdown解析器
const mdParser = new MarkdownIt();

function App() {
  const handleEditorChange = ({ html, text }) => {
    console.log('handleEditorChange', html, text);
  };

  const customPlugin = {
    name: 'custom-plugin',
    icon: 'fa fa-smile-o',
    title: 'Custom Plugin',
    action: (editor) => {
      editor.insertText('Hello from custom plugin!');
    },
  };

  return (
    <div className="App">
      <MdEditor
        value=""
        style={{ height: '500px' }}
        renderHTML={(text) => mdParser.render(text)}
        onChange={handleEditorChange}
        config={{
          view: {
            menu: true,
            md: true,
            html: true,
          },
          canView: {
            menu: true,
            md: true,
            html: true,
            fullScreen: true,
            hideMenu: true,
          },
          plugins: [customPlugin],
        }}
      />
    </div>

  );
}

export default App;

markdown-it

在React中使用Markdown解析器可以通过以下步骤实现。我们将使用react-markdown-editor-lite作为Markdown编辑器,并使用markdown-it作为Markdown解析器。

示例代码

import React, { useState } from 'react';
import MdEditor from 'react-markdown-editor-lite';
import MarkdownIt from 'markdown-it';
import 'react-markdown-editor-lite/lib/index.css';

// 初始化Markdown解析器
const mdParser = new MarkdownIt({
  html: true, // 启用HTML标签解析
  linkify: true, // 自动识别链接
  typographer: true, // 启用排版优化
  breaks: true, // 将换行符转换为<br>
});

function MarkdownEditor() {
  const [content, setContent] = useState('');

  const handleEditorChange = ({ html, text }) => {
    setContent(text);
  };

  return (
    <div className="markdown-editor">
      <MdEditor
        value={content}
        style={{ height: '500px' }}
        renderHTML={(text) => mdParser.render(text)}
        onChange={handleEditorChange}
      />
      <div className="markdown-preview">
        <h2>预览</h2>

        <div dangerouslySetInnerHTML={{ __html: mdParser.render(content) }} />
      </div>

    </div>

  );
}

export default MarkdownEditor;

解释

  1. 安装依赖
    确保安装了react-markdown-editor-litemarkdown-it

  2. 初始化Markdown解析器
    使用MarkdownIt初始化Markdown解析器,并配置一些常见选项:

  • html: true:启用HTML标签解析。

  • linkify: true:自动识别并转换链接。

  • typographer: true:启用排版优化(例如,将直引号转换为弯引号)。

  • breaks: true:将Markdown中的换行符转换为HTML的<br>标签。

  1. 创建React组件
    创建一个名为MarkdownEditor的React组件,包含Markdown编辑器和预览区域。

  2. 处理编辑器内容变化
    使用handleEditorChange函数处理编辑器内容变化,并更新组件状态。

  3. 渲染Markdown内容
    使用renderHTML属性将Markdown内容渲染为HTML,并在预览区域显示。

运行示例

将上述代码保存为一个React组件文件(例如,MarkdownEditor.jsx),然后在你的应用中导入并使用该组件:

import React from 'react';
import ReactDOM from 'react-dom';
import MarkdownEditor from './MarkdownEditor';

function App() {
  return (
    <div className="App">
      <h1>Markdown 编辑器示例</h1>

      <MarkdownEditor />
    </div>

  );
}

ReactDOM.render(<App />, document.getElementById('root'));

针对需要对md语法做自定义

import markdownItMermaid from 'markdown-it-mermaid';
import MarkdownIt from 'markdown-it';

this.mdParser = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true,
}).use(markdownItMermaid);

this.mdParser.block.ruler.disable(['code']);
// 自定义插件,将换行符转换为HTML换行标签
this.mdParser.core.ruler.push('replace_newlines', state => {
  state.tokens.forEach(token => {
    if (token.type === 'text') {
      token.content = token.content.replace(/\n/g, '<br/>');
    }
  });
});

针对语法块是属于block还是core,进入ruler调用Markdown-it aip,对md语法做自定义规则处理。

{
	"inline": {
		"ruler": {
			"__rules__": [
				{
					"name": "text",
					"enabled": true,
					"alt": []
				},
				{
					"name": "linkify",
					"enabled": true,
					"alt": []
				},
				{
					"name": "newline",
					"enabled": true,
					"alt": []
				},
				{
					"name": "escape",
					"enabled": true,
					"alt": []
				},
				{
					"name": "backticks",
					"enabled": true,
					"alt": []
				},
				{
					"name": "strikethrough",
					"enabled": true,
					"alt": []
				},
				{
					"name": "emphasis",
					"enabled": true,
					"alt": []
				},
				{
					"name": "link",
					"enabled": true,
					"alt": []
				},
				{
					"name": "image",
					"enabled": true,
					"alt": []
				},
				{
					"name": "autolink",
					"enabled": true,
					"alt": []
				},
				{
					"name": "html_inline",
					"enabled": true,
					"alt": []
				},
				{
					"name": "entity",
					"enabled": true,
					"alt": []
				}
			],
				"__cache__": null
		},
		"ruler2": {
			"__rules__": [
				{
					"name": "balance_pairs",
					"enabled": true,
					"alt": []
				},
				{
					"name": "strikethrough",
					"enabled": true,
					"alt": []
				},
				{
					"name": "emphasis",
					"enabled": true,
					"alt": []
				},
				{
					"name": "fragments_join",
					"enabled": true,
					"alt": []
				}
			],
				"__cache__": null
		}
	},
	"block": {
		"ruler": {
			"__rules__": [
				{
					"name": "table",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference"
					]
				},
				{
					"name": "code",
					"enabled": false,
					"alt": []
				},
				{
					"name": "fence",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote",
						"list"
					]
				},
				{
					"name": "blockquote",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote",
						"list"
					]
				},
				{
					"name": "hr",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote",
						"list"
					]
				},
				{
					"name": "list",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote"
					]
				},
				{
					"name": "reference",
					"enabled": true,
					"alt": []
				},
				{
					"name": "html_block",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote"
					]
				},
				{
					"name": "heading",
					"enabled": true,
					"alt": [
						"paragraph",
						"reference",
						"blockquote"
					]
				},
				{
					"name": "lheading",
					"enabled": true,
					"alt": []
				},
				{
					"name": "paragraph",
					"enabled": true,
					"alt": []
				}
			],
				"__cache__": null
		}
	},
	"core": {
		"ruler": {
			"__rules__": [
				{
					"name": "normalize",
					"enabled": true,
					"alt": []
				},
				{
					"name": "block",
					"enabled": true,
					"alt": []
				},
				{
					"name": "inline",
					"enabled": true,
					"alt": []
				},
				{
					"name": "linkify",
					"enabled": true,
					"alt": []
				},
				{
					"name": "replacements",
					"enabled": true,
					"alt": []
				},
				{
					"name": "smartquotes",
					"enabled": true,
					"alt": []
				},
				{
					"name": "text_join",
					"enabled": true,
					"alt": []
				},
				{
					"name": "replace_newlines",
					"enabled": true,
					"alt": []
				}
			],
		}
	},
	"renderer": {
		"rules": {}
	},
	"linkify": {
		"__opts__": {
			"fuzzyLink": true,
				"fuzzyEmail": true,
				"fuzzyIP": false
		},
		"__index__": -1,
			"__last_index__": -1,
			"__schema__": "",
			"__text_cache__": "",
	},
	"utils": {
		"lib": {
			"mdurl": {},
			"ucmicro": {
				"Any": {},
				"Cc": {},
				"Cf": {},
				"P": {},
				"S": {},
				"Z": {}
			}
		}
	},
	"helpers": {},
	"options": {
		"html": true,
			"xhtmlOut": false,
			"breaks": true,
			"langPrefix": "language-",
			"linkify": true,
			"typographer": true,
			"quotes": "“”‘’",
			"highlight": null,
			"maxNesting": 100
	},
	"mermaid": {
		"startOnLoad": true,
			"htmlLabels": true,
			"mermaidAPI": {}
	}
}

UmiJS 3.x 字体资源异步加载问题解决方案 2025-12-30
markdown编辑器图片上传优化 2025-12-30

评论区