index.jsx 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. setup: (editor) => {
  10. editor.on('change', () => {
  11. props.onChange(editor.getContent());
  12. console.log(editor.getContent())
  13. })
  14. },
  15. init_instance_callback: (editor) => {
  16. editorRef.current = editor;
  17. }
  18. });
  19. // eslint-disable-next-line react-hooks/exhaustive-deps
  20. }, [id])
  21. useImperativeHandle(ref, () => ({
  22. setContent: (val) => {
  23. if (editorRef.current) {
  24. editorRef.current.setContent(val)
  25. } else {
  26. const t = setInterval(() => {
  27. if (editorRef.current) {
  28. editorRef.current.setContent(val)
  29. clearInterval(t)
  30. console.log('-clearInterval-')
  31. }
  32. }, 200)
  33. }
  34. }
  35. }))
  36. return (
  37. <textarea id={id} />
  38. )
  39. })