本指南展示了如何使用 TinyMCE React 组件 在 React 应用中自行托管 TinyMCE。

前提条件

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

步骤

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

    # NPM 7+, extra double-dash is needed
    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 包。

    npm install tinymce
  4. 将 fs-extra 作为开发依赖项安装:

    npm install -D fs-extra
  5. 设置一个 postinstall 脚本,将 TinyMCE 复制到 public 目录,这将在每次安装后自动使 TinyMCE 和其他组件作为静态资源可用。

    添加 postinstall.js 文件。
    import fse from 'fs-extra';
    import path from 'path';
    
    const topDir = import.meta.dirname;
    fse.emptyDirSync(path.join(topDir, 'public', 'tinymce'));
    fse.copySync(path.join(topDir, 'node_modules', 'tinymce'), path.join(topDir, 'public', 'tinymce'), { overwrite: true });
    更新 package.json 中的 postinstall 目标以运行 postinstall.js 脚本。
    {
      // ... other content omitted for brevity ...
      "scripts": {
        // ... other scripts omitted for brevity ...
        "postinstall": "node ./postinstall.js"
      }
    }
  6. 将 public/tinymce 排除在 Git 跟踪之外

    # ... other rules omitted for brevity ...
    /public/tinymce/
  7. 在此实例中,运行 postinstall 以将 TinyMCE 复制到 public 目录。

    npm run postinstall
  8. 更新 App.jsx 以包含 Editor 组件。注意: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>
        </>
      );
    }
  9. 运行开发服务器以测试应用程序:

    npm run dev

其他资源