欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > React Hooks 封装可粘贴图片的输入框组件(wangeditor)

React Hooks 封装可粘贴图片的输入框组件(wangeditor)

2024/10/24 22:21:21 来源:https://blog.csdn.net/weixin_49720804/article/details/139501395  浏览:    关键词:React Hooks 封装可粘贴图片的输入框组件(wangeditor)

需求是需要一个文本框 但是可以支持右键或者ctrl+v粘贴图片,原生js很麻烦,那不如用插件来实现吧~我这里用的wangeditor插件,初次写初次用,可能不太好,但目前是可以达到实现需求的一个效果啦!后面再改进吧~

封装了个文本框组件,上代码吧直接:

import React, {useRef,useEffect,forwardRef,useImperativeHandle
} from "react";
import WangEditor from "wangeditor";
import { handleFetchPostJson } from "../../service/request";
import "./editimg.scss";// 过滤所有标签及属性
let reHtml =/(&lt;|<(?!img|p|\/p|h1|h2|h3|h4|h5|h6|\/h1|\/h2|\/h3|\/h4|\/h5|\/h6|span|\/span|br).*?>|&gt;)/gi;const EditorImgComponent = forwardRef(({ isPlot, onContentChange, editorConfig, isDialog }, ref) => {let wangEditor = useRef();const editorRef = useRef(null);useEffect(() => {if (editorRef.current) {wangEditor.current = new WangEditor(editorRef.current);const editor = wangEditor.current;editor.config.menus = editorConfig;// 允许粘贴图片editor.config.showLinkImg = false;editor.config.pasteFilterStyle = true;// 监控变化,同步更新到 textareaeditor.config.onchange = (html) => {onContentChange(html);};editor.config.placeholder ="<div>为了更加快速的定位查找问题,请您按照如下方式反馈相关信息:<br/>  # 云分析请提供项目编号、章节名称、问题描述;<br/># 云分析请提供分析参数和提示信息截图;<br/> # 云图汇工具 请描述问题,附上相关作图数据;<br/>支持粘贴图片,为了更好的展示效果,请将文案和图片换行展示</div>";// 粘贴时去掉标签editor.config.pasteTextHandle = (content) => {content = content.replace(/[\r\n]/g, "");content = content.replace(/\'/g, '"');content = content.replace(reHtml, "");return content;};editor.config.zIndex = 1;editor.config.customUploadImg = function (files, insert) {if (files[0].size / 1024 / 1024 > 2) {message.error("上传图片最大不超过2M!");return;}let formData = new FormData();formData.append("image", files[0]);handleFetchPostJson("v1/message/mess_pic/", formData, {"Content-Type": "multipart/form-data"}).then((res) => {if (res.code === 2000) {let time = new Date().getTime();insert(res.info + "?time=" + time);} else {message.error("上传失败,请重新上传!");}});};editor.create();return () => {editor.destroy();};}}, []);useImperativeHandle(ref,() => {return {editor: wangEditor.current};},[wangEditor.current]);return (<divref={editorRef}className={isPlot? "work-center-plot-content-editor": isDialog? "work-center-dialog-editor": "work-center-content-editor"}/>);}
);export default EditorImgComponent;

稍微微的描述一下吧
因为我在其他页面(也就是父组件)调用的话需要子组件和父组件的值保持一致,也就是说当父组件值清空时,子组件也要相应清空,父组件值变化时,子组件也要同样变化,所以用到forwardRef和useImperativeHandle,用法可以看下react官方文档。


父组件调用:

定义:

赋值:

我这里只需要图片所以只配置了图片 想要什么往里面加什么就好了 百度和wangediter文档都可以搜到配置项具体有哪些

父组件控制子组件的同步的重新赋值:

父组件控制子组件的同步的内容清空


效果展示:

操作展示 !!!话不多说了直接行动证明

完成!!!小马同学又进步啦~

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com