700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > [react]在antd pro中对Ueditor富文本编辑器进行封装

[react]在antd pro中对Ueditor富文本编辑器进行封装

时间:2021-04-27 18:01:50

相关推荐

[react]在antd pro中对Ueditor富文本编辑器进行封装

概述

Ueditor富文本编辑器,一个可以拖拽式编辑图片大小的编辑器,嗯这样的看起来牛逼一点,当然重要的是要免费开源,当然他还有其他功能,但我就看重他这点。

文章项目使用的是Ant Design Pro v5的脚手架,一些配置也都是以此为基础。如果你使用的是umi4也可以参考,具体配置下面也有提到

做的那些准备工作

先从github克隆一波Ueditor的代码

/fex-team/ueditor.git.

全局安装grunt, 如果你没有安装过的话,然后执行 grunt default

npm install grunt -ggrunt default

完成上述步骤后得到一个dist文件,我把他重命名成ueditor丢到我的项目中

在项目入口的html文件(src\pages\document.ejs)中引入ueditor编辑器文件

<script type="text/javascript" src="<%= context.config.publicPath +'ueditor/ueditor.config.js'%>"></script><script type="text/javascript" src="<%= context.config.publicPath +'ueditor/ueditor.all.js'%>"></script>

在umi4中时可以这样配置:

封装组件

1. Ueditor.jsx 文件

// import FileModal from '@/components/Modal/FileModal';// import { uploadFile } from '@/services/upload/upload';import {message } from 'antd';import {useEffect, useState } from 'react';import {ueditorConfig } from './ueditorConfig';declare const window: Window & {UE: any };interface Props {initData?: any; //输入值setContent?: Function; //输入时触发config?: any; //UEditor配置ueditorId?: any;}/*** 富文本编辑器组件* @description 在百度富文本编辑器的基础上进行了一次封装* @author 千万样子*/const UEditor: React.FC<Props> = (props) => {const {config, setContent, initData } = props;// console.log('UEditor.config:', config);//编辑图片选择模态框// const [editModalType, setEditModalType] = useState({ type: '' });//const ueditorId = props?.ueditorId || 'ueditor_id';const [ueditor, setUeditor] = useState<any>(null);useEffect(() => {initUeditor();}, []);/**初始化编辑器 */const initUeditor = () => {try {window.UE.delEditor(ueditorId);const editor = window.UE.getEditor(ueditorId, {...ueditorConfig,...config,});/* 指定这个 UI 是哪个编辑器实例上的,默认是页面上所有的编辑器都会添加这个按钮 */window.UE.registerUI('simpleupload',function (editor1: any, uiName: any) {// console.log(editor1, uiName);// 创建一个 buttonconst btn = new window.UE.ui.Button({// 按钮的名字name: uiName,// 提示title: '插入图片',// 需要添加的额外样式,可指定 icon 图标,图标路径参考常见问题 2cssRules: '',// 点击时执行的命令onclick: () => {// 打开文件选择器const a = document.getElementById('ueditor_btn_file');if (a) {a.click();}// setEditModalType({ type: 'select' });},});// 因为你是添加 button,所以需要返回这个 buttonreturn btn;},undefined /* 指定添加到工具栏上的哪个位置,默认时追加到最后 */,ueditorId,);editor.ready(() => {if (initData) {editor.setContent(initData); //设置默认值/表单回显}});editor.addListener('contentChange', function () {if (setContent) {setContent(editor.getContent());}});setUeditor(editor);} catch (error) {//如果出错重新加载一次setTimeout(() => {initUeditor();}, 100);}};/**选择图片文件时触发 */const fileOnChange = (e: any) => {// setEditModalType({ type: 'select' });const file = new FormData();file.append('file', e.target.files[0]);// const imgWidth = e.target.files[0];//此处更据你的实际情况添加图片上传接口// uploadFile(file)// .then((res) => {//if (res && res.code === 200) {// message.success(res.msg);// ueditor.focus();// ueditor.execCommand(// 'inserthtml',// `<p><img style="max-width:100%" src="${res.data.url}" /></p>`,// );//} else {// if (res) {// message.error(res.msg || `未知错误(code:${res.code})`);// }//}// })// .catch(() => {//message.error('上传失败');// });};return (<><script id={ueditorId} type="text/plain" /><inputtype={'file'}id={'ueditor_btn_file'}accept={'image/*'}onChange={(e) => fileOnChange(e)}style={{display: 'none' }}/>{/* <FileModalmultiple={false}maxNum={1}selectedNum={0}editModalType={editModalType}onSuccess={(data: any) => {setEditModalType({ type: '' });// console.log(data);if (ueditor) {ueditor.focus();ueditor.execCommand('inserthtml',`<p><img style="max-width:100%" src="${data[0].preview_url}" /></p>`,);}}}onCancel={() => {setEditModalType({ type: '' });}}modalVisible={editModalType.type}/> */}</>);};export default UEditor;

2. InputUEditor.jsx文件

为了能直接在antd 的表单中使用在UEditor.jsx文件的基础上有了InputUEditor.jsx文件

import UEditor from '@/components/UEditor/Ueditor';import React, {useState } from 'react';interface Props {value?: any; //输入值onChange?: Function; //输入时触发configOption?: any; //UEditor配置}/*** 富文本输入框组件* @description 适配antd Form 表单组件* @author 千万样子*/const InputUEditor: React.FC<Props> = (props) => {const {value, onChange, configOption } = props;// const ueInputRef = useRef(null);const [config] = useState(configOption);const [initData] = useState(value || '');const setContent = (e: any) => {if (!!onChange) {onChange(e);}};return <UEditor config={config} initData={initData} setContent={(e: any) => setContent(e)} />;};export default InputUEditor;

预览

参考

/fger/p/14333901.html

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。