Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在React环境下,是如何在弹出框中加载编辑器的? #18

Closed
LiuYnag opened this issue Nov 9, 2021 · 2 comments
Closed

Comments

@LiuYnag
Copy link

LiuYnag commented Nov 9, 2021

环境:React+AntDesign

代码

import React, { useEffect } from 'react';
import {  Modal } from 'antd';
import Cherry from 'cherry-markdown/dist/cherry-markdown.core';

useEffect(() => {
    if (visible) {
      const cherryInstance = new Cherry({
        id: 'markdown-container',
        value: '# welcome to cherry editor!',
      });
    }
  }, [visible]);


<Modal
  visible={visible}
  title="markdown"
  destroyOnClose
  maskClosable={false}
  width="80%"
>
  <div id="markdown-container"/>
</Modal>

问题描述:我本意是想在弹窗里面加载markdown编辑器的,但是目前好像是没有识别到Modal弹窗里面的DOM节点,直接在整个页面的根节点上面自动创建了一个ID为markdown-container的DIV容器。

问题:就是想请问,是如何将编辑器加载到弹出框中的目标容器的?

@humyfred
Copy link
Collaborator

humyfred commented Nov 9, 2021

主要是渲染的时机问题,当visible为true此时DOM上还未出现Modal内id为markdown-container的div 元素,cherry默认就会在根节点创建。

正确做法是保证元素出来之后再调用创建cherry的实例

@LiuYnag
Copy link
Author

LiuYnag commented Nov 10, 2021

更改了一下代码:

const editorRef = useRef<HTMLDivElement>(null);
useEffect(() => {
    if (editorRef.current) {
      const cherryEditor = new Cherry({
        id: 'markdown-container',
        value: '# welcome to cherry editor!',
        editor: {
          theme: 'default',
          defaultModel: 'edit&preview',
        },
        toolbars: {
          toolbar : ['bold', 'italic', 'strikethrough', '|', 'color', 'header', '|', 'list', { insert: [ 'image', 'link', 'hr', 'br', 'code', 'formula', 'toc', 'table', 'line-table', 'bar-table' ], }, 'settings'],
        },
      });
    } 
  }, [editorRef.current])

根据节点是否存在来判断渲染时机

@LiuYnag LiuYnag closed this as completed Nov 10, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants