本指南展示了如何使用 TinyMCE React 组件 在 React 应用中自行托管 TinyMCE。
前提条件
此过程需要 Node.js(和 NPM)。
步骤
使用 Vite 和 React SWC 创建一个名为
tinymce-react-demo的新 React 项目。# NPM 7+, extra double-dash is needed npm create vite@5 tinymce-react-demo -- --template react-swc
进入项目目录并安装
@tinymce/tinymce-reactcd tinymce-react-demo && npm install @tinymce/tinymce-react
安装
tinymce包。npm install tinymce
将
fs-extra作为开发依赖项安装:npm install -D fs-extra
设置一个
添加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" } }将
public/tinymce排除在 Git 跟踪之外# ... other rules omitted for brevity ... /public/tinymce/
在此实例中,运行
postinstall以将 TinyMCE 复制到public目录。npm run postinstall
更新
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> </> ); }运行开发服务器以测试应用程序:
npm run dev
其他资源
有关 TinyMCE React 集成示例,请参阅:the tinymce-react storybook。
有关集成 TinyMCE 高级插件的指南,请参阅:Using premium plugins。
有关自定义信息:
TinyMCE 集成,请参阅:TinyMCE React integration technical reference。
TinyMCE,请参阅:Basic setup。
React 应用程序,请参阅:Getting Started with Vite 或 the React documentation。