react集成tinymce
reacttinymce

在项目中需要使用到富文本编辑器,之前用的kindeditor,但是,kindeditor的图片上传,无法自己定义。而且kindeditor 好像已经很久不维护了。所以,简单调研了一下之后就选择用tinymce。
其实,tinymce官方是有 tinymce-react 这个包的。但是测试之后发现,会去请求官方的静态文件。由于某些(你懂的)原因,请求国外服务器的稳定性是非常不好的,所以还是以自己的本地的加载为主。
下面就写一个react集成tinymce的demo.
本地加载依赖的文件的方法就不写了,自己搭建cdn也好,项目集成也好,都可以。


import React, {useEffect, useRef} from "react";
import {v4 as uuidv4} from 'uuid';
import _ from "lodash";

const TinymceEditor = ({value,onChange,height,uploadAction})=>{
    const editorId = "editor_"+uuidv4();
    const tinymceEditorRef = useRef();

    useEffect(()=>{
        let editor = tinymceEditorRef.current;
        if(editor){
            if(value !== editor.getContent()){
                editor.setContent(value);
            }
        }

    },[value]);

    useEffect(()=>{
        if(editorId){
            tinymce.init({
                selector: `#${editorId}`,
                branding: false,
                language:'zh_CN',
                height: height,
                menubar:false,
                plugins: [
                    'advlist autolink link image lists'
                ],
                toolbar: 'undo redo | styleselect | bold italic bullist numlist forecolor backcolor | alignleft aligncenter alignright alignjustify | outdent indent |' +
                    ' link image',
                init_instance_callback: (editor)=>{
                    tinymceEditorRef.current = editor;
                },
                images_upload_handler: function (blobInfo, succFun, failFun){
                    let file = blobInfo.blob();
                    let formData = new FormData();
                    formData.append("file",file);
                    if(uploadAction){
                        uploadAction(formData).then((result)=>{
                            succFun(result.url);
                        });
                    }
                },
                setup: function(editor) {
                    editor.on('change input', _.debounce(()=>{
                        if(onChange){
                            console.log(editor.getContent())
                            onChange(editor.getContent());
                        }
                    },500));
                }
            });
        }
    },[]);

    return <>
        <textarea id={editorId}/>
    </>

}
export default TinymceEditor

看看效果:
image5.png



看着还不错的样子。

如果遇到报错,请参考: react集成tinymce遇到错误解决

暂无评论