index.jsx 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import React, { forwardRef, useRef, useEffect, useMemo, useImperativeHandle } from 'react'
  2. import { uploadImage } from '@/services/image'
  3. export default forwardRef((props, ref) => {
  4. const editorRef = useRef()
  5. const id = useMemo(() => `mce-${Math.random().toString(36).substring(2, 10)}`, [])
  6. useEffect(() => {
  7. window.tinymce.init({
  8. selector: `#${id}`,
  9. menubar: false,
  10. language: 'zh_CN',
  11. plugins: 'image',
  12. image_description: false, // 禁用图片描述
  13. image_dimensions: false, // 禁用图片宽高设置
  14. toolbar: 'blocks fontfamily fontsize bold italic backcolor alignleft aligncenter alignright alignjustify image outdent indent undo redo removeformat',
  15. setup: (editor) => {
  16. editor.on('change', () => {
  17. props.onChange(editor.getContent());
  18. console.log(editor.getContent())
  19. })
  20. },
  21. init_instance_callback: (editor) => {
  22. editorRef.current = editor;
  23. },
  24. images_upload_handler: (blobInfo, progress) => {
  25. return new Promise((resolve, reject) => {
  26. const formData = new FormData();
  27. formData.append('file', blobInfo.blob(), blobInfo.filename());
  28. uploadImage(formData).then(resolve)
  29. })
  30. }
  31. });
  32. // eslint-disable-next-line react-hooks/exhaustive-deps
  33. }, [id])
  34. useImperativeHandle(ref, () => ({
  35. setContent: (val) => {
  36. if (editorRef.current) {
  37. editorRef.current.setContent(val)
  38. } else {
  39. const t = setInterval(() => {
  40. if (editorRef.current) {
  41. editorRef.current.setContent(val)
  42. clearInterval(t)
  43. console.log('-clearInterval-')
  44. }
  45. }, 200)
  46. }
  47. }
  48. }))
  49. return (
  50. <textarea id={id} />
  51. )
  52. })