react利用wangEditor写评论和@功能

先引入wangeditor写评论功能

import React, { useEffect, useState, useRef, forwardRef, useImperativeHandle } from 'react';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { Button, Card, Col, Form, List, Row, Select, Tag, message, Mentions } from 'antd';
import { wsPost, wsGet } from '@models/BaseModel';
import { ListItemDataType, fakeList } from '../../List';
import { LikeOutlined, LoadingOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';
import ArticleListContent from '../../ArticleListContent/index';
import './style.less';
import closeImg from '../../../../image/close.svg';
// import { createToolbar } from '@wangeditor/editor/dist/editor/src';
import { position, offset } from 'caret-pos';
import { IDomEditor, DomEditor, IModalMenu, SlateNode, Boot } from '@wangeditor/editor';
import mentionModule, { MentionElement } from '@wangeditor/plugin-mention';
import PersonModal from './personModal';
// Extend menuconst IconText = ({ type, text }) => {switch (type) {case 'star-o':return (<span><StarOutlined style={{ marginRight: 8 }} />{text}</span>);case 'like-o':return (<span><LikeOutlined style={{ marginRight: 8 }} />{text}</span>);case 'message':return (<span><MessageOutlined style={{ marginRight: 8 }} />{text}</span>);default:return null;}
};const Comments = forwardRef((props, CommentRef) => {const [editor, setEditor] = useState(null); // 存储 editor 实例const [html, setHtml] = useState();const [loading, setLoading] = useState(true);const [commentVis, setCommentVis] = useState(false);const [commentParentId, setCommentParentId] = useState('0'); //父级idconst [messageApi, contextHolder] = message.useMessage();const [buttonLoading, setButtonLoading] = useState(false);const [personList, setPersonList] = useState([]); //人员const [isModalVisible, setIsModalVisible] = useState(false);const formRef = useRef();// const toolbar = DomEditor.getToolbar(editor)// const curToolbarConfig = toolbar.getConfig()// console.log( curToolbarConfig.toolbarKeys )useImperativeHandle(CommentRef, () => ({closeHand: () => {if (editor == null) return;setCommentVis(false);editor.clear();setEditor(null);},}));const withAttachment = editor => {const { isInline, isVoid } = editor;const newEditor = editor;newEditor.isInline = elem => {const type = DomEditor.getNodeType(elem);if (type === 'attachment') return true; // 针对 type: attachment ,设置为 inlinereturn isInline(elem);};return newEditor;};useEffect(() => {console.log(props.dataList, props.type, 'nbsp');}, [props.dataList]);useEffect(() => {Boot.registerPlugin(withAttachment);Boot.registerModule(mentionModule);wsGet({url: '/api/problem/getUsers',handler: res => {const { code, data, msg } = res;switch (code) {case 20000: {setPersonList(data);break;}default:message.error(msg);break;}},});}, []);const toolbarConfig = {toolbarKeys: ['bold','underline','italic',// 'emotion',{key: 'group-image', // 必填,要以 group 开头title: '图片', // 必填iconSvg:'<svg viewBox="0 0 1024 1024"><path d="M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-384 256 320h64l224.01-192z"></path></svg>', // 可选menuKeys: ['uploadImage'], // 下级菜单 key ,必填},{key: 'group-video', // 必填,要以 group 开头title: '视频', // 必填iconSvg:'<svg viewBox="0 0 1024 1024"><path d="M981.184 160.096C837.568 139.456 678.848 128 512 128S186.432 139.456 42.816 160.096C15.296 267.808 0 386.848 0 512s15.264 244.16 42.816 351.904C186.464 884.544 345.152 896 512 896s325.568-11.456 469.184-32.096C1008.704 756.192 1024 637.152 1024 512s-15.264-244.16-42.816-351.904zM384 704V320l320 192-320 192z"></path></svg>', // 可选menuKeys: ['uploadVideo'], // 下级菜单 key ,必填},'codeBlock',],};const editorConfig = {placeholder: '请输入内容...',MENU_CONF: {uploadImage: {server: '/api/problem/uploadimag',fieldName: 'files',maxFileSize: 20 * 1024 * 1024,meta: {ifToken: '1',},metaWithUrl: true,headers: {token: localStorage.getItem('X-Auth-Token'),},onBeforeUpload() {setButtonLoading(true);message.loading({content: '上传中',duration: 0,});},onSuccess(file, res) {setButtonLoading(false);message.destroy();console.log(`${file.name} 上传成功`, res);},onError(file, err, res) {// console.log(`${file.name} 上传出错`, err, res)message.error(res.msg);},customInsert(res, insertFn) {console.log(res);// 从 res 中找到 url alt href ,然后插入图片insertFn(res.data[0].filePath, res.data[0].fileName, res.data[0].filePath);},},uploadVideo: {server: '/api/problem/uploadimag',fieldName: 'files',maxFileSize: 200 * 1024 * 1024,meta: {ifToken: '1',},metaWithUrl: true,headers: {token: localStorage.getItem('X-Auth-Token'),},timeout: 15 * 1000,onBeforeUpload() {console.log(messageApi, 'shipinzou');setButtonLoading(true);message.loading({content: '上传中',duration: 0,});},onSuccess(file, res) {setButtonLoading(false);message.destroy();console.log(`${file.name} 上传成功`, res);},onError(file, err, res) {// console.log(`${file.name} 上传出错`, err, res)message.error(res.msg);},customInsert(res, insertFn) {console.log(res);// 从 res 中找到 url alt href ,然后插入图片insertFn(res.data[0].filePath, res.data[0].fileName, res.data[0].filePath);},},},EXTEND_CONF: {mentionConfig: {showModal, // 必须hideModal, // 必须},},};function showModal(editor) {// 获取光标位置,定位 modalconst domSelection = document.getSelection();const domRange = domSelection.getRangeAt(0);if (domRange == null) return;const selectionRect = domRange.getBoundingClientRect();// 获取编辑区域 DOM 节点的位置,以辅助定位const containerRect = editor.getEditableContainer().getBoundingClientRect();// 显示 modal 弹框,并定位// PS:modal 需要自定义,如 <div> 或 Vue React 组件setIsModalVisible(true);console.log(selectionRect, containerRect, '展示');// 当触发某事件(如点击一个按钮)时,插入 mention 节点}function insertMention(id, name) {const mentionNode = {type: 'mention', // 必须是 'mention'value: name, // 文本info: { id }, // 其他信息,自定义children: [{ text: '' }], // 必须有一个空 text 作为 children};editor.restoreSelection(); // 恢复选区editor.deleteBackward('character'); // 删除 '@'editor.insertNode(mentionNode); // 插入 mentioneditor.move(1); // 移动光标}function hideModal(editor) {setIsModalVisible(false);console.log(editor, '隐藏');// 隐藏 modal}// 及时销毁 editoruseEffect(() => {return () => {if (editor == null) return;editor.destroy();// editor.MENU_CONF['uploadImage'] =setEditor(null);};}, [editor]);function extractDataInfoValues(inputString) {const regex = /data-info="([^"]*)"/g;const dataInfoValues = [];let match;while ((match = regex.exec(inputString)) !== null) {const decodedValue = decodeURIComponent(match[1]);dataInfoValues.push(JSON.parse(decodedValue).id);}return dataInfoValues;}function handleText() {// console.log(editor.getHtml(), html, editor.getText(), 'sdsdsds');const ids = extractDataInfoValues(html);if (editor.isEmpty()) {message.error('内容不可为空');return;}let commentType = '';switch (props.type) {case '1':commentType = 'reason';break;case '2':commentType = 'tempProject';break;case '3':commentType = 'longProject';break;case '4':commentType = 'validateProject';break;case '5':commentType = 'validateSummary';break;case '6':commentType = 'reviewRecords';break;case '7':commentType = 'proConclution';break;}let param = {commentType: commentType,content: html,problemId: props.id,parentId: commentParentId,ids: ids,};wsPost({url: '/api/problem/insertComment',data: param,handler: res => {const { code, data, msg } = res;switch (code) {case 20000: {if (editor == null) return;editor.clear();setCommentVis(false);message.success('新增成功');props.getQuery();break;}default:message.error(msg);break;}},});}function extractContent(inputString, startSymbol, endSymbol) {const regex = new RegExp(`${startSymbol}(.*?)${endSymbol}(?!\\S)`, 'g');const matches = inputString.matchAll(regex);const result = Array.from(matches, match => match[1]);return result;}function printHtml() {if (editor == null) return;}const addCommpent = id => {setCommentParentId(id);setCommentVis(true);};const handleClose = () => {setCommentVis(false);editor.clear();setEditor(null);};const changeEditor = editor => {setHtml(editor.getHtml()), console.log(editor.getHtml(), editor.getText(), 'xiugai');};return (<><ButtonclassName="commontClass"style={{ position: 'absolute', right: '10px', top: '10px', zIndex: '2' }}type="primary"loading={buttonLoading}onClick={() => {addCommpent(0);}}>新增</Button><ArticleListContent data={props.dataList} addCommpent={addCommpent} />{commentVis && <div style={{ width: '100%', height: '350px' }} />}{commentVis && (<div id="editcontent" className="commontClass" style={{ border: '1px solid #ccc', zIndex: 100, marginTop: '15px', position: 'fixed', bottom: '0', width: 'calc(100vw - 250px)', minHeight: '300px' }}><div style={{ position: 'absolute', right: '10px', bottom: '10px', zIndex: 2 }}><Button type="primary" loading={buttonLoading} onClick={handleText}>发表</Button></div><div className="closeImg" onClick={handleClose}><img src={closeImg} alt="" /></div><Toolbar editor={editor} defaultConfig={toolbarConfig} mode="default" style={{ borderBottom: '1px solid #ccc' }} /><EditordefaultConfig={editorConfig}value={html}onCreated={setEditor}onChange={editor => {changeEditor(editor);}}mode="default"style={{ height: '300px' }}/>{isModalVisible && <PersonModal hideModal={hideModal} insertMention={insertMention}></PersonModal>}</div>)}{/* <div style={{ marginTop: '15px' }}>{html}</div> */}{/* 渲染html */}{/* <div dangerouslySetInnerHTML={{__html: `'<p>hello <strong>world</strong>.</p><p><img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="test" data-href="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" style="width: 30%;"/><img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="test" data-href="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" style=""/><img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="test" data-href="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" style=""/><img src="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" alt="test" data-href="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg" style=""/></p>'`}}></div> */}</>);
});export default Comments;

评论递归ArticleListContent,jsx

import { Avatar, List, Space, Card } from 'antd';
import React, { useEffect, useState } from 'react';
import moment from 'moment';
import './index.less';
import { fakeList } from '../List';
import { LikeOutlined, LoadingOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';const getMarginLeftNum = num => {return 30 * num;
};const GetContent = props => {const [loading, setLoading] = useState(false);const IconText = ({ icon, text, id, num }) => {if (num <= 1) {return (<Space><divclassName="commontClass"onClick={() => {props.addCommpent(id);}}>{React.createElement(icon)}{text}</div></Space>);}return <Space />;};console.log(props.num, 'props.num');return (<div>{props.item.map((o, index) => {return (<div key={index} style={{ marginLeft: getMarginLeftNum(props.num + 1) }}><Listsize="large"loading={loading}rowKey="id"itemLayout="vertical"dataSource={[o]}renderItem={item => (<List.Item key={o.id}><Card title={item.creator} bordered={false} extra={[<IconText icon={MessageOutlined} key="message" type="message" id={item.id} num={props.num} />]}><div className={'description'} dangerouslySetInnerHTML={{ __html: item.content }} /><div className={'extra'}><em>{moment(item.createDate).format('YYYY-MM-DD HH:mm')}</em></div></Card></List.Item>)}/>{o.children && <GetContent item={o.children} num={props.num + 1} addCommpent={props.addCommpent} />}</div>);})}</div>);
};const ArticleListContent = props => {const [loading, setLoading] = useState(false);const IconText = ({ icon, text, id }) => (<Space><divclassName="commontClass"onClick={() => {props.addCommpent(id);}}>{React.createElement(icon)}{text}</div></Space>);return (<div className={'listContent'} style={{ minHeight: '200px' }}>{!props.data && <div style={{ fontSize: '18px', fontWeight: '500', color: '#8d8989', display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: '50px' }}>暂无内容</div>}{props.data &&props.data.map((item, index) => {item, 'item';if (!item.children) {return (<div key={index} className="commentItem"><Card><Listsize="large"loading={loading}rowKey="id"key={index}itemLayout="vertical"dataSource={[item]}renderItem={item => (<List.Item key={item.id}><Card title={item.creator} bordered={false} extra={[<IconText icon={MessageOutlined} key="message" type="message" id={item.id} />]}><div className={'description'} dangerouslySetInnerHTML={{ __html: item.content }} /><div className={'extra'}><em>{moment(item.createDate).format('YYYY-MM-DD HH:mm')}</em></div></Card></List.Item>)}/></Card></div>);}return (<div key={index} className="commentItem"><Card><Listsize="large"loading={loading}key={index}rowKey="id"itemLayout="vertical"dataSource={[item]}renderItem={item => (<List.Item key={item.id}><Card title={item.creator} bordered={false} extra={[<IconText icon={MessageOutlined} key="message" type="message" id={item.id} />]}><div className={'description'} dangerouslySetInnerHTML={{ __html: item.content }} /><div className={'extra'}><em>{moment(item.createDate).format('YYYY-MM-DD HH:mm')}</em></div></Card></List.Item>)}/>{item.children && <GetContent item={item.children} num={1} addCommpent={props.addCommpent} />}</Card></div>);})}</div>);
};export default ArticleListContent;

@功能自定义的组件 personModal.jsx

import { Modal, Form, Input, Select, message } from 'antd';
import { ModalForm, ProFormTextArea } from '@ant-design/pro-components';
import { wsPost, wsGet } from '@models/BaseModel';
import React, { ReactDOM, useEffect, useRef, useState } from 'react';
const { Option } = Select;export default function CsModal(props) {const selectRef = useRef();const [personList, setPersonList] = useState([]); //人员const [topPosition, setTopPosition] = useState('');const [leftPosition, setLeftPosition] = useState('');useEffect(() => {// 获取光标位置const domSelection = document.getSelection();const domRange = domSelection?.getRangeAt(0);if (domRange == null) return;const rect = document.getElementById('editcontent').getBoundingClientRect();const rect1 = domRange.getBoundingClientRect();// // 定位 modalconsole.log(rect, rect1, 'top left');setTopPosition(`${rect1.top - rect.top - 5}px`);setLeftPosition(`${rect1.left - rect.left + 10}px`);// focus inputselectRef.current.focus();wsGet({url: '/api/problem/getUsers',handler: res => {const { code, data, msg } = res;switch (code) {case 20000: {setPersonList(data);break;}default:message.error(msg);break;}},});}, []);const onChangeSelect = e => {let name = personList.find(item => item.externalId === e);props.insertMention(e, name.name);props.hideModal();};return (<Selectref={selectRef}showSearchallowClearplaceholder="请选择提出人"style={{ width: '150px', position: 'absolute', top: topPosition, left: leftPosition }}optionFilterProp="children"filterOption={(input, option) => option?.children?.toLowerCase().indexOf(input?.toLowerCase()) >= 0}filterSort={(optionA, optionB) => {return optionA?.children?.toLowerCase().localeCompare(optionB?.children?.toLowerCase());}}onChange={onChangeSelect}>{personList.length > 0 &&personList.map(item => {return (<Option key={item.externalId} value={item.externalId}>{item.name}</Option>);})}</Select>);
}

实现效果
评论的效果

@的效果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/99071.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

文件包含漏洞利用的几种方法

文章目录 安装环境启动环境漏洞花式利用蚁剑连接图片马读取敏感文件&#xff08;hosts&#xff09;读取该网站的php源码 代码审计 安装环境 安装phpstudy&#xff0c;下载MetInfo 5.0.4版本软件&#xff0c;复制到phpstudy目录下的www目录中。 打开phpstudy&#xff0c;访问浏…

Typora for Mac(Markdown文本编辑器)

Typora是一款简洁、直观的跨平台Markdown编辑器软件。它提供了一个非常直观和简单的界面&#xff0c;让用户可以更轻松地编写和编辑Markdown语言的文档。 Typora具有实时预览功能&#xff0c;这意味着你可以在编辑Markdown文档的同时立即看到最终的效果。它允许用户快速切换编辑…

视频监控/视频云存储EasyCVR平台接入华为ivs3800平台提示400报错,如何解决?

开源EasyDarwin视频监控TSINGSEE青犀视频平台EasyCVR能在复杂的网络环境中&#xff0c;将分散的各类视频资源进行统一汇聚、整合、集中管理&#xff0c;在视频监控播放上&#xff0c;视频云存储/安防监控汇聚平台可支持1、4、9、16个画面窗口播放&#xff0c;可同时播放多路视频…

【个人博客系统网站】项目的发布 · 通过公网IP访问我们的网站 · 思考总结

【JavaEE】进阶 个人博客系统&#xff08;6&#xff09; 文章目录 【JavaEE】进阶 个人博客系统&#xff08;6&#xff09;1. 项目发布1.1 后端代码修改1.1.1 数据库密码1.1.2 端口号修改1.1.3 文件保存地址修改1.1.4 静态资源映射修改 1.2 云服务器1.2.1 建库建表1.2.2 必要…

通过rabbitmq生成延时消息,并生成rabbitmq镜像

通过rabbitmq生成延时消息队列&#xff0c;并生成rabbitmq镜像 整体描述1. 使用场景2. 目前问题3. 前期准备 具体步骤1. 拉取镜像2. 运行镜像3. 安装插件4. 代码支持4.1 config文件4.2 消费监听4.2 消息生产 5. 功能测试 镜像操作1. 镜像制作2. 镜像导入 总结 整体描述 1. 使用…

vue集成mars3d后,basemaps加不上去

首先&#xff1a; <template> <div id"centerDiv" class"mapcontainer"> <mars-map :url"configUrl" οnlοad"onMapload" /> </div> </template> <script> import MarsMap from ../component…

Vue + Element UI 前端篇(三):工具模块封装

Vue Element UI 实现权限管理系统 前端篇&#xff08;三&#xff09;&#xff1a;工具模块封装 封装 axios 模块 封装背景 使用axios发起一个请求是比较简单的事情&#xff0c;但是axios没有进行封装复用&#xff0c;项目越来越大&#xff0c;会引起越来越多的代码冗余&am…

Kotlin(五) 循环语句

目录 For循环 关键字 until step downTo Java中主要有两种循环语句&#xff1a;while循环和for循环。而Kotlin也提供了while循环和for循环&#xff0c;其中while循环不管是在语法还是使用技巧上都和Java中的while循环没有任何区别&#xff0c;因此我们就直接跳过不进行讲解…

小白学go基础06-了解切片实现原理并高效使用

slice&#xff0c;中文多译为切片&#xff0c;是Go语言在数组之上提供的一个重要的抽象数据类型。在Go语言中&#xff0c;对于绝大多数需要使用数组的场合&#xff0c;切片实现了完美替代。并且和数组相比&#xff0c;切片提供了更灵活、更高效的数据序列访问接口。 切片究竟是…

项目管理工具:实现项目科学管理的利器

什么是项目管理工具 项目管理工具是指用于协助规划、组织、执行和监控项目活动的软件或应用程序。它们提供了一系列功能和工具&#xff0c;帮助项目管理人员和团队有效地管理项目进度、资源分配、任务协作以及沟通等方面的工作。项目管理工具的目标是提高团队的工作效率、优化…

浅谈Mysql读写分离的坑以及应对的方案 | 京东云技术团队

一、主从架构 为什么我们要进行读写分离&#xff1f;个人觉得还是业务发展到一定的规模&#xff0c;驱动技术架构的改革&#xff0c;读写分离可以减轻单台服务器的压力&#xff0c;将读请求和写请求分流到不同的服务器&#xff0c;分摊单台服务的负载&#xff0c;提高可用性&a…

vue 浏览器记住密码后,自动填充账号密码错位

亲测有效&#xff01;&#xff01;! 遇到的场景&#xff1a; 浏览器记住密码后&#xff0c;登录时自动填充账号密码&#xff0c;由于登录时只需要这两个字段所以没问题&#xff0c;见图一&#xff0c;但注册时&#xff0c;账号密码不在一处&#xff0c;见图二 原本账号应该在…