React-Quill 是Antd推薦使用的富文本編輯器,此文記錄一下最近在項目中使用它遇到的一些問題。
首先,大家在百度相關資料時,應當搜索React-Quill,而不是Quill。
github點這裏:https://github.com/zenoamaro/react-quill
安裝依賴這些就都不說了,只記錄乾貨....
調用示例:
<ReactQuill
theme="snow"
value={content || ''}
onChange={onChange}
modules={modules}
formats={formats}
/>
modules 是對編輯器功能的配置,此處是從組件的state中拿出來的,具體配置如下:
modules: {
toolbar: {
container: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline', 'strike', 'blockquote'],
[{ list: 'ordered' }, { list: 'bullet' }],
['link', 'image'],
['clean'],
],
handlers: {
image() {
imageHandler.call(this, props.action);
},
},
},
},
這裏需要注意的是,toolbar的配置需要和formats屬性想匹配,此處我是直接在組件外聲明瞭一個全名變量:
const formats = [
'header',
'bold',
'italic',
'underline',
'strike',
'blockquote',
'list',
'bullet',
'indent',
'link',
'image',
];
特別說明的一點是:由於React-Quill默認是將圖片轉換成base64的。但是由於一般情況想生成出來的base64字符串會特別長,所以這個地方我們採用的方式時先將圖片上傳到服務端,然後用上傳成功之後返回的url來替換掉圖片的base64。Qeact-Quill提供了handlers屬性來對圖片進行單獨處理,代碼如下:
function imageHandler(action) {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = () => {
const file = input.files[0];
const fd = new FormData();
fd.append('file', file);
const hide = message.loading('上傳中...', 0);
upload(action, fd).then(res => {
if (res) {
const range = this.quill.getSelection();
this.quill.insertEmbed(range.index, 'image', res.url);
hide();
}
});
};
}
簡述一下,大概方法就是利用Input File來上傳圖片的~這裏的upload方法是我們自己封裝的圖片上傳方法。最重要的一步是,需要在上傳成功後的回調裏對進行替換圖片src的操作。首先通過this.quill拿到Quill實例,注意這裏有一個大坑,在使用過程中始終拿不到這個Quill實例,後來發現需要將此處的this指向配置對象。所以此處的imageHandler函數是一個組件外的全局函數。
通過這件事情,發現JavaScript的this指向真是一個很重要的東西呀~剛開始其實是知道應該就是this指向的問題,但是嘗試各種方法之後無法解決。後在我司前端主程大大的指點下解決了~手動比心心~
在這個過程中onChange函數需要將編輯器的值傳遞出來並在函數體中將值綁定到具體的字段上,這樣就可以將該參數按照與後端約定好的方式發送過去即可。