react + tinymce 初始化函数 onInit 与 setup

1,521 阅读2分钟

@tinymce/tinymce-react 包中的 Editor 组件具有两个与初始化相关的函数:onInitsetup

onInit 函数:

onInit 函数是 Editor 组件的一个回调函数,当 TinyMCE 编辑器初始化完成后被触发。你可以通过在 Editor 组件上设置 onInit 属性来指定相应的处理函数。这个函数会接收一个参数 editor,它是初始化后的 TinyMCE 编辑器实例。

使用 onInit 函数,你可以在编辑器初始化完成后执行一些自定义的操作,例如调用编辑器的方法、注册插件、设置键盘快捷键等。

以下是一个示例,演示如何在 onInit 函数中执行一些操作:

import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

const MyEditor = () => {
  const handleEditorInit = (editor) => {
    // 在编辑器初始化完成后执行一些操作
    console.log('Editor initialized:', editor);
    editor.setContent('<p>Initial content</p>');
  };

  return (
    <Editor
      apiKey="YOUR_API_KEY"
      initialValue="<p>Initial content</p>"
      init={{
        height: 500,
        menubar: false,
        plugins: '...',
        toolbar: '...',
      }}
      onInit={handleEditorInit}
    />
  );
};

export default MyEditor;

在上述示例中,我们定义了一个 handleEditorInit 函数,用于在编辑器初始化完成后输出一条消息,并将初始内容设置为 <p>Initial content</p>

setup 函数:

setup 函数是 TinyMCE 编辑器的配置项之一,通过 init 属性传递给 Editor 组件。它是一个函数,接收一个参数 editor,用于在编辑器初始化期间执行自定义的设置和操作。

使用 setup 函数,你可以注册自定义插件、自定义按钮、修改编辑器的配置等。它提供了更高级的自定义选项。

以下是一个示例,演示如何在 setup 函数中执行一些操作:

import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

const MyEditor = () => {
  const handleEditorSetup = (editor) => {
    // 在编辑器初始化期间执行一些操作
    console.log('Editor setup:', editor);
    editor.ui.registry.addButton('customButton', {
      text: 'Custom Button',
      onAction: function() {
        editor.insertContent('Custom button clicked!');
      }
    });
  };

  return (
    <Editor
      apiKey="YOUR_API_KEY"
      initialValue="<p>Initial content</p>"
      init={{
        height: 500,
        menubar: false,
        plugins: '...',
        toolbar: '...',
        setup: handleEditorSetup
      }}
    />
  );
};

export default MyEditor;

在上述示例中,我们定义了一个 handleEditorSetup 函数,用于在编辑器初始化期间注册一个自定义按钮。这个函数会在编辑器初始化过程中被调用,并传递当前的编辑器实例作为参数;

总结

oninit 在编辑器初始化完成之后,用于赋值editor 或者 调用 editorapi;

setup 在编辑器初始化期间,可以注册自定义插件、自定义按钮、修改编辑器的配置等;