跳到主要内容

WangEditor5-React

一、认识


wangEditor 5 官方文档

二、安装


  • 安装@wangeditor/editor@wangeditor/editor-for-react依赖

    yarn add @wangeditor/editor @wangeditor/editor-for-react -S

三、使用


import React, { useState, useEffect } from "react";
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import axios from "axios";
import { DomEditor, IDomEditor } from "@wangeditor/editor";

type InsertFnType = (url: string, alt: string, href: string) => void;
type EditorPropsType = {
value?: string;
onChange?: (value: any) => void;
disabled: boolean;
};

function MyEditor(props: EditorPropsType) {
const { value, onChange, disabled } = props;
const [editor, setEditor] = useState<IDomEditor | null>(null);
const [html, setHtml] = useState(value);
const toolbarConfig = {
toolbarKeys: [
"headerSelect",
"blockquote",
"bold",
"underline",
"italic",
"color",
"bgColor",
"fontSize",
"fontFamily",
"lineHeight",
"bulletedList",
"numberedList",
"uploadImage",
],
};

const handleUpload = async (file: File) => {
const formData = new FormData();
formData.append("file", file);
formData.append("innerPublic", "public");
const {
data: {
originResult: { download_url_https },
},
} = await axios.post("/config/upload/img.node", formData);
return download_url_https;
};

const editorConfig = {
placeholder: "请输入内容...",
readOnly: disabled,
scroll: true,
MENU_CONF: {
uploadImage: {
async customUpload(file: File, insertFn: InsertFnType) {
const result = await handleUpload(file);
insertFn(result, result, result);
},
},
},
};

const handleChange = (editor: IDomEditor | null) => {
onChange?.(editor?.getHtml());
};

useEffect(() => {
// 获取富文本编辑器的 Toolbar 默认配置
// if (editor) {
// const toolbar = DomEditor.getToolbar(editor);
// const curToolbarConfig = toolbar.getConfig();
// console.log(curToolbarConfig.toolbarKeys); // 当前菜单排序和分组
// }
return () => {
if (editor == null) return;
editor.destroy();
setEditor(null);
};
}, [editor]);
useEffect(() => {
setHtml(value);
}, [value]);

return (
<>
<div style={{ border: "1px solid #ccc", zIndex: 100, marginTop: "15px" }}>
<Toolbar
editor={editor}
defaultConfig={toolbarConfig}
mode="default"
style={{ borderBottom: "1px solid #ccc" }}
/>
<Editor
defaultConfig={editorConfig}
value={html}
onCreated={setEditor}
onChange={(editor) => handleChange(editor)}
mode="default"
style={{ height: "300px" }}
/>
</div>
</>
);
}

export default MyEditor;