本指南展示如何使用 TinyMCE React 组件,将 .zip 包中的 TinyMCE 自托管并懒加载到 React 应用中。

前置条件

此过程需要 Node.js(和 NPM)。

操作步骤

  1. 使用 Vite 和 React SWC 创建一个名为 tinymce-react-demo 的新 React 项目。

    # NPM 7+,需要额外的双连字符
    npm create vite@5 tinymce-react-demo -- --template react-swc
  2. 进入项目目录并安装 @tinymce/tinymce-react

    cd tinymce-react-demo && npm install @tinymce/tinymce-react
  3. 将 TinyMCE zip 中 tinymce/js 文件夹的内容解压到 public 文件夹。这将使 tinymce 作为静态资源对应用程序可用。

  4. 在 ./eslint.config.js 文件中,将 'public/tinymce' 添加到 ignores 数组中。

    Diff of .eslint.config.js
    export default tseslint.config(
    -  { ignores: ['dist'] },
    +  { ignores: ['dist', 'public/tinymce'] },
       {
         extends: [js.configs.recommended, ...tseslint.configs.recommended],
         files: ['**/*.{ts,tsx}'],
  5. 使用以下代码片段更新 App.jsx。注意:tinymceSrcScript 引用公共 tinymce 时使用绝对根路径。

    import { useRef } from 'react';
    import { Editor } from '@tinymce/tinymce-react';
    import './App.css';
    
    export default function App() {
      const editorRef = useRef(null);
      const log = () => {
        if (editorRef.current) {
          console.log(editorRef.current.getContent());
        }
      };
      return (
        <>
          <Editor
            tinymceScriptSrc='/tinymce/tinymce.min.js'
            licenseKey='gpl'
            onInit={(_evt, editor) => editorRef.current = editor}
            initialValue='<p>This is the initial content of the editor.</p>'
            init={{
                height: 500,
                menubar: false,
                plugins: [
                  'advlist', 'autolink', 'lists', 'link', 'image', 'charmap',
                  'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
                  'insertdatetime', 'media', 'table', 'preview', 'help', 'wordcount'
                ],
                toolbar: 'undo redo | blocks | ' +
                  'bold italic forecolor | alignleft aligncenter ' +
                  'alignright alignjustify | bullist numlist outdent indent | ' +
                  'removeformat | help',
                content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
              }}
          />
          <button onClick={log}>Log editor content</button>
        </>
      );
    }
  6. 运行开发服务器以测试应用程序:

    npm run dev

其他资源