100 lines
2.1 KiB
JavaScript
100 lines
2.1 KiB
JavaScript
import { Editor as ReactEditor, Toolbar } from "@wangeditor/editor-for-react";
|
|
import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
|
|
import { normalizeEmptyHtml } from "../../utils";
|
|
import "@wangeditor/editor/dist/css/style.css";
|
|
|
|
/**
|
|
* 富文本编辑器组件
|
|
*/
|
|
const Editor = forwardRef(({
|
|
value,
|
|
onChange,
|
|
disabled,
|
|
}, ref) => {
|
|
const [editor, setEditor] = useState(null);
|
|
|
|
const [html, setHtml] = useState("");
|
|
|
|
useEffect(() => {
|
|
setHtml(value);
|
|
}, [value]);
|
|
|
|
useEffect(() => {
|
|
if (!editor)
|
|
return;
|
|
if (disabled)
|
|
editor.disable();
|
|
else editor.enable();
|
|
}, [disabled]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (!editor)
|
|
return;
|
|
editor.destroy();
|
|
setEditor(null);
|
|
};
|
|
}, [editor]);
|
|
|
|
useImperativeHandle(ref, () => ({
|
|
getEditorInstance: () => editor,
|
|
getHtml: () => editor && editor.getHtml(),
|
|
setHtml: (value) => {
|
|
editor && editor.setHtml(value);
|
|
},
|
|
getText: () => editor && editor.getText(),
|
|
}));
|
|
|
|
const handleCreated = (editor) => {
|
|
setEditor(editor);
|
|
if (disabled)
|
|
editor.disable();
|
|
};
|
|
|
|
const handleChange = (editor) => {
|
|
setHtml(editor.getHtml());
|
|
onChange?.(normalizeEmptyHtml(editor.getHtml()));
|
|
};
|
|
|
|
// 工具栏配置
|
|
const toolbarConfig = {
|
|
excludeKeys: [
|
|
"group-image",
|
|
"group-video",
|
|
"insertLink",
|
|
"emotion",
|
|
"todo",
|
|
],
|
|
};
|
|
|
|
// 编辑器配置
|
|
const editorConfig = {
|
|
placeholder: "请输入内容...",
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<div style={{ border: "1px solid #ccc" }}>
|
|
<Toolbar
|
|
editor={editor}
|
|
defaultConfig={toolbarConfig}
|
|
mode="default"
|
|
style={{ borderBottom: "1px solid #ccc" }}
|
|
/>
|
|
<ReactEditor
|
|
defaultConfig={editorConfig}
|
|
value={html}
|
|
onCreated={handleCreated}
|
|
onChange={handleChange}
|
|
mode="default"
|
|
style={{ height: "500px", overflowY: "hidden" }}
|
|
/>
|
|
</div>
|
|
</>
|
|
);
|
|
});
|
|
|
|
Editor.displayName = "Editor";
|
|
|
|
export default Editor;
|