1- import React , { useState , createRef , useRef , useEffect } from 'react' ;
1+ import React , { useState , createRef , useRef , useEffect , useImperativeHandle , useMemo } from 'react' ;
22import CodeMirror , { ICodeMirror } from './components/CodeMirror' ;
33import MarkdownPreview , { MarkdownPreviewProps } from '@uiw/react-markdown-preview' ;
44import ToolBar , { IToolBarProps } from './components/ToolBar' ;
@@ -20,7 +20,20 @@ export interface IMarkdownEditor extends ICodeMirror {
2020 options ?: CodeMirror . EditorConfiguration ,
2121}
2222
23- export default function MarkdownEditor ( props : IMarkdownEditor ) {
23+ export interface MarkdownEditorRef {
24+ editor ?: CodeMirror . Editor ;
25+ preview ?: HTMLDivElement | null ;
26+ }
27+
28+ export default React . forwardRef < MarkdownEditorRef , IMarkdownEditor > ( MarkdownEditor ) ;
29+
30+ function MarkdownEditor (
31+ props : IMarkdownEditor ,
32+ ref ?:
33+ | ( ( instance : MarkdownEditorRef ) => void )
34+ | React . RefObject < MarkdownEditorRef >
35+ | null
36+ ) {
2437 const {
2538 prefixCls = 'md-editor' , className,
2639 onChange,
@@ -35,6 +48,12 @@ export default function MarkdownEditor(props: IMarkdownEditor) {
3548 const [ editor , setEditor ] = useState < CodeMirror . Editor > ( ) ;
3649 const container = useRef < HTMLDivElement > ( null ) ;
3750 const containerEditor = useRef < HTMLDivElement > ( null ) ;
51+
52+ useImperativeHandle ( ref , ( ) => ( {
53+ editor : editor ,
54+ preview : previewContainer . current ,
55+ } ) ) ;
56+
3857 useEffect ( ( ) => {
3958 if ( codeMirror . current ) {
4059 setEditor ( codeMirror . current . editor ) ;
@@ -48,24 +67,25 @@ export default function MarkdownEditor(props: IMarkdownEditor) {
4867 containerEditor : containerEditor . current ,
4968 editorProps : props
5069 }
70+ const codeEditor = useMemo ( ( ) => (
71+ < CodeMirror
72+ visibleEditor = { visibleEditor }
73+ { ...codemirrorProps }
74+ ref = { codeMirror }
75+ onChange = { ( editor , data ) => {
76+ setValue ( editor . getValue ( ) ) ;
77+ onChange && onChange ( editor , data , editor . getValue ( ) )
78+ } }
79+ />
80+ ) , [ visibleEditor , codemirrorProps ] )
5181 return (
5282 < div ref = { container } >
5383 < div className = { `${ prefixCls || '' } ${ className || '' } ` } >
5484 < ToolBar { ...toolBarProps } toolbars = { toolbarsMode } mode />
5585 < ToolBar { ...toolBarProps } toolbars = { toolbars } />
5686 < div className = { `${ prefixCls } -content` } >
5787 < div className = { `${ prefixCls } -content-editor` } ref = { containerEditor } >
58- { visibleEditor && (
59- < CodeMirror
60- visibleEditor = { visibleEditor }
61- { ...codemirrorProps }
62- ref = { codeMirror }
63- onChange = { ( editor , data ) => {
64- setValue ( editor . getValue ( ) ) ;
65- onChange && onChange ( editor , data , editor . getValue ( ) )
66- } }
67- />
68- ) }
88+ { visibleEditor && codeEditor }
6989 </ div >
7090 < MarkdownPreview
7191 { ...previewProps }
0 commit comments