1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import React, { forwardRef, useRef, useEffect, useMemo, useImperativeHandle } from 'react'
  2. export default forwardRef((props, ref) => {
  3. const editorRef = useRef()
  4. const id = useMemo(() => `mce-${Math.random().toString(36).substring(2, 10)}`, [])
  5. useEffect(() => {
  6. window.tinymce.init({
  7. selector: `#${id}`,
  8. menubar: false,
  9. branding:false,
  10. setup: (editor) => {
  11. editor.on('change', () => {
  12. props.onChange(editor.getContent());
  13. console.log(editor.getContent())
  14. })
  15. },
  16. init_instance_callback: (editor) => {
  17. editorRef.current = editor;
  18. }
  19. });
  20. // eslint-disable-next-line react-hooks/exhaustive-deps
  21. }, [id])
  22. useImperativeHandle(ref, () => ({
  23. setContent: (val) => {
  24. if (editorRef.current) {
  25. editorRef.current.setContent(val)
  26. } else {
  27. const t = setInterval(() => {
  28. if (editorRef.current) {
  29. editorRef.current.setContent(val)
  30. clearInterval(t)
  31. console.log('-clearInterval-')
  32. }
  33. }, 200)
  34. }
  35. }
  36. }))
  37. return (
  38. <textarea id={id} />
  39. )
  40. })