先引入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>);
}
实现效果