如何在CKEditor5-ReactJS或.Net项目中添加MathType和ChemType插件
React项目集成带MathType/ChemType插件的CKEditor5实现方案
1. 依赖安装
先安装所需的三方依赖包,执行以下命令即可:
npm install @ckeditor/ckeditor5-react @ckeditor/ckeditor5-build-classic @wiris/mathtype-ckeditor5
如果使用yarn作为包管理器,将npm install替换为yarn add即可。
2. 编辑器组件实现
可直接参考以下最小可运行Demo代码,封装可复用的CKEditor组件:
import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import MathType from '@wiris/mathtype-ckeditor5'; // 给编辑器注入MathType、ChemType插件 ClassicEditor.builtinPlugins = [ ...ClassicEditor.builtinPlugins, MathType ]; // 配置工具栏,新增公式、化学公式按钮 ClassicEditor.defaultConfig = { toolbar: { items: [ 'heading', 'bold', 'italic', 'bulletedList', 'numberedList', 'blockQuote', 'MathType', 'ChemType', // 两个插件对应的工具栏按钮 'undo', 'redo' ] }, // Wiris插件基础配置 mathType: { serviceProviderProperties: { URI: 'https://www.wiris.net/demo/plugins/app/', server: 'java' } }, language: 'zh-cn' }; function CKEditorWithMath() { return ( <div> <CKEditor editor={ ClassicEditor } data="<p>初始内容</p>" onChange={ ( event, editor ) => { const data = editor.getData(); // 此处可将编辑器输出内容存储到对应状态 console.log( data ); } } /> </div> ); } export default CKEditorWithMath;
3. 注意事项
- 示例中使用的是Wiris公开演示服务,仅可用于开发测试,商用场景需要自行部署Wiris服务或者申请商用授权,替换配置中的
URI地址即可 - 如果项目基于Create React App创建,默认无法直接处理CKEditor的SVG等静态资源,需要使用
@craco/craco修改webpack配置,或者直接使用CKEditor自定义构建版本 - 编辑完成后需要回显公式时,直接渲染编辑器输出的HTML内容即可,公式会自动以图片形式正常渲染
- ChemType化学公式编辑能力是MathType插件自带的,不需要额外安装其他依赖,只需在工具栏配置中加上
ChemType按钮即可正常使用
内容的提问来源于stack exchange,提问作者Bhavin Patel
相关产品推荐
相关产品推荐

