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 menu

const 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'); //父级id
    const [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 ,设置为 inline
            return 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) {
        // 获取光标位置,定位 modal
        const 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); // 插入 mention
        editor.move(1); // 移动光标
    }
    function hideModal(editor) {
        setIsModalVisible(false);
        console.log(editor, '隐藏');
        // 隐藏 modal
    }
    // 及时销毁 editor
    useEffect(() => {
        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 (
        <>
            <Button
                className="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' }} />
                    <Editor
                        defaultConfig={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>
                    <div
                        className="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) }}>
                        <List
                            size="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>
            <div
                className="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>
                                    <List
                                        size="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>
                                <List
                                    size="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();

        // // 定位 modal
        console.log(rect, rect1, 'top left');
        setTopPosition(`${rect1.top - rect.top - 5}px`);
        setLeftPosition(`${rect1.left - rect.left + 10}px`);
        // focus input
        selectRef.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 (
        <Select
            ref={selectRef}
            showSearch
            allowClear
            placeholder="请选择提出人"
            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>
    );
}

实现效果
评论的效果

@的效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
React是一个流行的JavaScript库,用于构建用户界面。实现登录功能通常需要以下步骤: 1. 创建一个表单组件,包含用户名和密码输入框以及提交按钮。 2. 在表单组件中添加事件处理程序,当用户点击提交按钮时,将用户名和密码发送到服务器进行验证。 3. 如果验证成功,则将用户信息存储在本地(如cookie或localStorage)中,并在应用程序中设置用户已登录的状态。 4. 在需要登录的页面或组件中检查用户是否已登录,如果未登录则重定向到登录页面。 以下是一个简单的登录组件示例: ``` import React, { useState } from 'react'; const Login = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = async (event) => { event.preventDefault(); const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await response.json(); if (data.success) { localStorage.setItem('user', JSON.stringify(data.user)); // set the user as logged in } else { // show error message } } return ( <form onSubmit={handleSubmit}> <label> Username: <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} /> </label> <label> Password: <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} /> </label> <button type="submit">Log In</button> </form> ); }; export default Login; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值