index.jsx 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import React, { useState, useEffect } from "react";
  2. import "@wangeditor/editor/dist/css/style.css";
  3. import { Editor, Toolbar } from "@wangeditor/editor-for-react";
  4. function MyEditor(props) {
  5. const {
  6. value,
  7. onChange = (e) => {
  8. setHtml(e);
  9. },
  10. toolbarConfig = {
  11. excludeKeys: [
  12. "insertImage",
  13. "viewImageLink",
  14. "editImage",
  15. "uploadImage",
  16. "uploadVideo",
  17. ],
  18. },
  19. editorConfig = {
  20. placeholder: "请输入内容...",
  21. },
  22. readonly = false,
  23. } = props;
  24. const [editor, setEditor] = useState(null); // 存储 editor 实例
  25. const [html, setHtml] = useState("");
  26. console.log(props, "MyEditor");
  27. // 模拟 ajax 请求,异步设置 html
  28. useEffect(() => {
  29. console.log(editor );
  30. setHtml(value);
  31. }, [value]);
  32. // 及时销毁 editor
  33. useEffect(() => {
  34. return () => {
  35. if (editor == null) return;
  36. editor.destroy();
  37. setEditor(null);
  38. };
  39. }, [editor]);
  40. function insertText() {
  41. if (editor == null) return;
  42. editor.insertText(" hello ");
  43. }
  44. function printHtml() {
  45. if (editor == null) return;
  46. console.log(editor.getHtml());
  47. }
  48. return !readonly ? (
  49. <>
  50. <div style={{ border: "1px solid #ccc", zIndex: 100, marginTop: "15px" }}>
  51. <Toolbar
  52. editor={editor}
  53. defaultConfig={toolbarConfig}
  54. mode="default"
  55. style={{ borderBottom: "1px solid #ccc" }}
  56. />
  57. <Editor
  58. defaultConfig={editorConfig}
  59. value={html}
  60. onCreated={setEditor}
  61. onChange={(editor) => onChange(editor.getHtml())}
  62. mode="default"
  63. style={{ height: "500px" }}
  64. />
  65. </div>
  66. </>
  67. ) : (
  68. <div dangerouslySetInnerHTML={{ __html: value }}></div>
  69. );
  70. }
  71. export default MyEditor;