加载,并渲染tinymce 由于tinymce体积较大,在项目中编辑器如果不是常用的,就不需要打开网页就加载tinymce。
比较好的办法是,在要使用的时候,去加载tinymce相关的资源。
所以利用webpack的importapi实现懒加载。api详情地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 componentDidMount () { this .loadTinFile() .then(() => { tinymce.init({ selector: '#tinymceEdit' , }) }) } loadTinFile () { return Promise .all([ import ( 'tinymce' ), import ( 'tinymce/skins/lightgray/skin.min.css' ) ]) .then(() => { return Promise .all([ import ( './tinymce_zh_CN' ), import ( 'tinymce/themes/modern' ) ]) }) } render () { return ( <div className='tinymce' > <textarea id='tinymceEdit' /> </div> ) }
react渲染出id tinymceEdit的dom
import加载tinymce文件,import api是异步的,会返回Promise
tinymce.init初始化编辑器
webpackChunkName “tinymce”, 在编译的时候,生成名字为tinymce.chunk.js的文件
至此就会渲染tinymce编辑器了。
编辑器内容样式 tinymce使用iframe渲染出编辑部分,所以外包定义的样式是无效的,需要在iframe内部加载css样式。
在初始化的时候,使用content_css参数定义css样式的链接地址,
tinymce在初始化的时候,就会添加link css链接
1 2 3 4 tinymce.init({ selector: '#tinymceEdit' , content_css: `${process.env.PUBLIC_URL} /tinymce/content.css` , })
这里css是被当成静态资源使用,所以无法被webpack处理
插件 插件使用文档,查看plugins文档
插件的使用,需要先加载插件文件,再初始化的时候,配置plugins字段,让tinymce加载插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 const tinyPlugins = [ 'code' , 'fullscreen' , 'link' , 'textcolor' , 'lists' , 'advlist' , 'wordcount' , 'table' , 'preview' , 'print' , 'insertdatetime' , 'charmap' , 'pagebreak' , 'media' ] componentDidMount () { this .loadTinFile() .then(() => { tinymce.init({ selector: '#tinymceEdit' , toolbar: [ 'code | undo redo | bold italic underline strikethrough subscript superscript removeformat blockquote | forecolor backcolor h2 p kityformula | numlist bullist | fullscreen' , ' fontsizeselect fontselect | alignleft aligncenter alignright alignjustify | outdent indent | link unlink openlink | upimg' , 'pagebreak insertdatetime charmap | table tabledelete tableinsertrowbefore tableinsertrowafter tabledeleterow tablemergecells tablesplitcells | print preview | media' ], plugins: tinyPlugins.join(',' ) }) }) } loadTinFile () { return Promise .all([ ...tinyPlugins.map((item ) => { return import ( `tinymce/plugins/${item} ` ) }) ]) }
这里使用的插件,都是使用在toolbar里面,如果未加载和定义插件,toolbar里面的按钮就不会显示
待续···
初始文本
Failed prop type: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly.
添加按钮 setup ,在编辑器渲染前,执行的回调
使用addButton添加按钮,
execCommand(‘mceToggleFormat’) ,编辑器内部命令,添加对应的格式
onPostRender ,当按钮显示后的回调执行,绑定编辑器初始化。
formatter.formatChanged ,在编辑器内,鼠标选择的部分和参数相同的时候回调,让按钮突出显示
公式编辑器 图片上传