index.tsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import '@wangeditor/editor/dist/css/style.css'; // 引入 css
  2. import { useState, useEffect } from 'react';
  3. import { Editor, Toolbar } from '@wangeditor/editor-for-react';
  4. import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
  5. function MyEditor(props: any) {
  6. const { data } = props;
  7. // editor 实例
  8. const [editor, setEditor] = useState<IDomEditor | null>(null);
  9. // 编辑器内容
  10. const [html, setHtml] = useState('');
  11. useEffect(() => {
  12. setHtml(data);
  13. }, []);
  14. // 工具栏配置
  15. const toolbarConfig: Partial<IToolbarConfig> = {};
  16. // 编辑器配置
  17. const editorConfig: Partial<IEditorConfig> = {
  18. placeholder: '请输入内容...',
  19. };
  20. // 及时销毁 editor ,重要!
  21. useEffect(() => {
  22. return () => {
  23. if (editor == null) return;
  24. editor.destroy();
  25. setEditor(null);
  26. };
  27. }, [editor]);
  28. return (
  29. <>
  30. <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
  31. <Toolbar
  32. editor={editor}
  33. defaultConfig={toolbarConfig}
  34. mode="default"
  35. style={{ borderBottom: '1px solid #ccc' }}
  36. />
  37. <Editor
  38. defaultConfig={editorConfig}
  39. value={html}
  40. onCreated={setEditor}
  41. onChange={(el) => setHtml(el.getHtml())}
  42. mode="default"
  43. style={{ height: '300px', overflowY: 'hidden' }}
  44. />
  45. </div>
  46. </>
  47. );
  48. }
  49. export default MyEditor;