前言:記錄一下工作中使用的比較方便的富文本組件,本文包含
1. 初始化。
2. 將html文本賦值給編輯器。
3. 在編輯器中上傳圖片。
4. 獲取編輯器中的內容
一 、 引入
yarn add wangeditor / npm install wangeditor
import E from 'wangeditor';
初始化編輯器:
componentDidMount(){
this.initEditor();
}
initEditor() {
const elem = this.refs.editorElem;
const editor = new E(elem);
this.editor = editor;
editor.create()
}
二、 給編輯器賦值,上傳本地圖片插入編輯器
獲取編輯器的內容
this.editor.txt.html();
//賦值也是用這個方法
this.editor.txt.html( <p>hello world!!!</p> )
上傳圖片,這裏我用的是傳FormData格式的圖片給後臺,返回我base64編碼的圖片,然後將突然插入編輯器的富文本文檔流中的方法。
// 增強一下剛剛的initEditor
initEditor() {
const elem = this.refs.editorElem;
const editor = new E(elem);
this.editor = editor;
// 編輯編輯區域zIndex,默認10000,修改這個可以避免編輯框zIndex等級太高遮擋住其他顯示。
//editor.customConfig.zIndex = 100
// 限制一次最多上傳 10 張圖片
editor.customConfig.uploadImgMaxLength = 10;
editor.customConfig.customUploadImg = function (files, insert) {
// files 是 input 中選中的文件列表
if (files[0]) {
const formData = new FormData();
formData.append('file', files[0], 'cover.jpg');
net.postFileUpload(formData).then(res => {
if (res.responseCode === "00") {
net.getFileImage(res.content).then(res => {
if (res.responseCode === "00") {
insert('data:image/jpeg;base64,' + res.content);
}
})
} else {
message.error(res.response_msg, 2)
}
});
} else {
// Toast.info('請選擇要上傳的圖片')
}
};
editor.create()
}
================================================
以上就基本滿足了我現在的開發需求,這篇文章只是對wangeditor編輯器做一個快速入門。更多操作請參考