本指南展示了如何使用 TinyMCE React 组件 将来自 Tiny Cloud 的 TinyMCE 集成到 React 应用程序中。

前置条件

此过程需要 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. 更新 App.jsx,从 tinymce/tinymce-react 引入 Editor,如下所示。

    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
            apiKey='no-api-key'
            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>
        </>
      );
    }
  4. 使用您的 Tiny Cloud API key 更新 apiKey 属性。

  5. 运行开发服务器以测试应用程序:

    npm run dev

其他资源