Editor.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import '@wangeditor/editor/dist/css/style.css' // 引入 css
  2. import React, { useState, useEffect } from 'react'
  3. import { Editor, Toolbar } from '@wangeditor/editor-for-react'
  4. import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
  5. import { UploadFile, GetFile } from "@/api"
  6. type InsertFnType = (url: string, poster: string) => void
  7. export default ({
  8. html,
  9. onChange
  10. }: {
  11. html: string,
  12. onChange: (html: string) => void
  13. }) => {
  14. // editor 实例
  15. const [editor, setEditor] = useState<IDomEditor | null>(null)
  16. // 工具栏配置
  17. const toolbarConfig: Partial<IToolbarConfig> = {}
  18. // 自定义插入
  19. const customInsert = (res: any, insertFn: InsertFnType) => {
  20. console.log('自定义插入:', res);
  21. // insertFn(url, alt, href)
  22. };
  23. // 自定义上传
  24. const customUpload = async (file: File, insertFn: InsertFnType) => {
  25. console.log('自定义上传:', file);
  26. const form = new FormData();
  27. form.append('file', file);
  28. const res = await UploadFile(form);
  29. const fileId = res?.[0]?.id;
  30. insertFn(`/api/File/Download?fileId=${fileId}`, file.name);
  31. return;
  32. };
  33. // 编辑器配置
  34. const editorConfig: Partial<IEditorConfig> = {
  35. placeholder: '请输入内容...',
  36. MENU_CONF: {
  37. uploadImage: {
  38. customUpload,
  39. customInsert
  40. },
  41. uploadVideo: {
  42. customUpload,
  43. customInsert
  44. }
  45. }
  46. }
  47. // 及时销毁 editor
  48. useEffect(() => {
  49. return () => {
  50. if (editor == null) return
  51. editor.destroy()
  52. setEditor(null)
  53. }
  54. }, [editor])
  55. return (
  56. <>
  57. <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
  58. <Toolbar
  59. editor={editor}
  60. defaultConfig={toolbarConfig}
  61. mode="default"
  62. style={{ borderBottom: '1px solid #ccc' }}
  63. />
  64. <Editor
  65. defaultConfig={editorConfig}
  66. value={html}
  67. onCreated={setEditor}
  68. onChange={(editor) => onChange?.(editor.getHtml())}
  69. mode="default"
  70. style={{ height: '500px', overflowY: 'hidden' }}
  71. />
  72. </div>
  73. </>
  74. )
  75. }