之前寫項目時用到過 wangEditor 和 markdown ,隻是當時忘了總結。以至于現在需要用 wangEditor 了還得翻以前的項目,隻是以前用的不是react,需要更改代碼。廢話不多說,下面總結一下 在 react 中如何使用 wangEditor 富文本編輯器。
1、安裝 wangEditor
npm install wangeditor
2、引入 wangEditor
3、使用 wangEditor
這個可以看看 wangEditor 官網,根據自己需要修改。下面放一下我的代碼:
constructor(props, context) {
super(props, context);
this.state = {
editorHtmlContent: '',
editorTextContent: ''
}
}
componentDidMount() {
const div1 = this.refs.div1;
const div2 = this.refs.div2;
const editor = new E(div1, div2);
// 監聽内容的變化,實時更新到 state 中
editor.customConfig.onchange = html => {
// console.log(editor.txt.html());
// console.log(editor.txt.text());
this.setState({
editorTextContent: editor.txt.text(),
editorHtmlContent: editor.txt.html()
})
};
editor.customConfig.menus = [
//編輯預設的菜單配置如下:
'head', // 标題
'bold', // 粗體
'fontSize', // 字号
'fontName', // 字型
'italic', // 斜體
'underline', // 下劃線
'strikeThrough', // 删除線
'foreColor', // 文字顔色
'backColor', // 背景顔色
'link', // 插傳入連結接
'list', // 清單
'justify', // 對齊方式
'quote', // 引用
'emoticon', // 表情
'image', // 插入圖檔
'table', // 表格
// 'video', // 插入視訊
'code', // 插入代碼
'undo', // 撤銷
'redo' // 重複
];
editor.customConfig.debug = true; //開啟debug模式
editor.customConfig.uploadFileName = 'file'; //自定義 fileName
editor.customConfig.uploadImgServer = '/api/imageUpload'; // 上傳圖檔到伺服器
editor.customConfig.uploadImgHooks = {
before : function(xhr, editor, files) {
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖檔檔案
// 圖檔上傳之前觸發
},
success : function(xhr, editor, result) {
// 圖檔上傳并傳回結果,圖檔插入成功之後觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是伺服器端傳回的結果
},
fail : function(xhr, editor, result) {
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是伺服器端傳回的結果
// 圖檔上傳并傳回結果,但圖檔插入錯誤時觸發
alert("上傳成功,插入失敗");
},
error : function(xhr, editor) {
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
// 圖檔上傳出錯時觸發
alert("上傳失敗,請重試");
},
timeout : function(xhr, editor) {
alert("上傳逾時!");
},
customInsert: function (insertImg, result, editor) {
// insertImg 是插入圖檔的函數,editor 是編輯器對象,result 是伺服器端傳回的結果
// 圖檔上傳并傳回結果,自定義插入圖檔的事件(而不是編輯器自動插入圖檔!!!)
var data =result.relativePath;
// alert(data);
if(result.result_msg=="圖檔上傳成功") {
message.success(result.result_msg);
insertImg(`api/` + data); //這裡的 api 是我為了跨域
}
}
};
editor.create()
}
<div ref="div1" className="toolbar"></div>
<div ref="div2" className="text"></div>