react-quill 富文本组件封装,简单易用

930 阅读1分钟

react-quill 使用

实现功能

  1. 与 ant design 的 form 表单结合,可通过 Form 获取组件内部数据
  2. 自定义上传图片功能,可上传至图床

组件代码

import ReactQuill from 'react-quill';
import {useCallback, useEffect, useMemo, useRef, useState} from "react";
import {Button, message} from "antd";
import {PublicServices} from "@services/modules/public";
import axios from "axios";

const MarkDown = (props: any) => {
    let QuillRefs: any = useRef(null);
    const customImageHandler = () => {
        const input: any = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();
        input.onchange = async () => {
            const file = input.files[0];
            const formData = new FormData();
            formData.append(file?.name, file);
            const faceUrlResult: any = await PublicServices.getUrl(encodeURIComponent(file?.name));
            const noAuthUrl = faceUrlResult?.faceUrl?.split('?')[0];
            const result: any = {method: 'put', url: faceUrlResult?.faceUrl, data: file};
            axios(result).then((res: any) => {
                if (res?.status === 200) {
                    message.success("上传成功")
                    let quill = QuillRefs?.current?.getEditor();
                    const cursorPosition = quill.getSelection().index;
                    quill.insertEmbed(cursorPosition, 'image', noAuthUrl);
                    quill.setSelection(cursorPosition + 1);
                }
            });
        };
    };

    const modules = useMemo(() => ({
        toolbar: {
            container: [
                [{'header': [1, 2, 3, 4, 5, 6, false]}],
                ['bold', 'italic', 'underline', 'strike', 'blockquote'],
                [{'color': []}, {'background': []}],
                [{'list': 'ordered'}, {'list': 'bullet'}, {'indent': '-1'}, {'indent': '+1'}, {'align': []}],
                ['link', 'image'],
            ],
            handlers: {
                image: () => {
                    customImageHandler.call(this);
                },
            },
        },
    }), [])


    return (
        <>
            <ReactQuill
                ref={(el) => {
                    QuillRefs.current = el;
                }}
                readOnly={props?.disabled}
                modules={modules}
                preserveWhitespace
                theme='snow'
                placeholder='请输入'
                {...props}
            />
        </>
    );
};

export default MarkDown;

同理可以定制化第三方的组件,实现表头操作的扩展,嵌入上传视频,Emoji 等等功能。