react-quill 网上找了自定义上传图片的方式。测试后都失败,会报:
react-quill addRange(): The given range isn't in document.
解决办法:
关键点: 在创建实例后,去重新设置image的uploader方法。(蓝色部分)
代码:
const [content, setContent] = useState(''); const quillEdit = useRef(); const options = useMemo(() => ({ toolbar: { container: [ // ['bold', 'italic', 'underline', 'strike'], // toggled buttons // ['blockquote', 'code-block'], // ['link', 'image', 'formula'],
// [{ 'header': 1 }, { 'header': 2 }], // custom button values // [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'list': 'check' }], // [{ 'script': 'sub' }, { 'script': 'super' }], // superscript/subscript // [{ 'indent': '-1' }, { 'indent': '+1' }], // outdent/indent // [{ 'direction': 'rtl' }], // text direction
// [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown // [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
// [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme // [{ 'font': [] }], // [{ 'align': [] }],
// ['clean'] ['image'], ], }, })) const quillImageUploader = () => { const input = document.createElement('input') input.setAttribute('type', 'file') input.setAttribute('accept', 'image/*') input.setAttribute('multiple', 'multiple') input.click() input.onchange = async () => { Array.from(input.files).forEach(item => { const formData = new FormData(); formData.append('file', item, ''); R.upload('/api/admin/m/upload', formData).then(({ model }) => { const { path } = model; var cursorPosition = quillEdit.current.getEditor().getSelection(true).index; quillEdit.current.getEditor().insertEmbed(cursorPosition, "image", UPLOAD_BASE_PATH + path); quillEdit.current.getEditor().setSelection(cursorPosition + 1); }) }) } } const setQuillEdit = (r) => { quillEdit.current = r; if (r) { r.getEditor().getModule('toolbar').handlers.image = quillImageUploader } } return ( <ReactQuill ref={o => setQuillEdit(o)} modules={options} style={{ height: 400, width: 375 }} theme='snow' value={content} onChange={setContent} /> )
标签:current,const,自定义,image,react,quillEdit,input,quill From: https://www.cnblogs.com/ckaaaa/p/18248385