wangEditor轻量级web富文本
// 安装一下依赖
npm i @wangeditor/editor
npm i @wangeditor/editor-for-react
import axios from 'axios'
import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import '@wangeditor/editor/dist/css/style.css'
function MyEditor() {
// editor 实例
const [editor, setEditor] = useState(null)
// 编辑器内容
const [html, setHtml] = useState('')
// 模拟 ajax 请求,异步设置 html
useEffect(() => {
}, [])
// 工具栏配置
const toolbarConfig = {}
// 编辑器配置
const editorConfig = {
placeholder: '请输入内容...',
MENU_CONF: {
uploadImage: {
// 单个文件的最大体积限制,默认为 2M
maxFileSize: 4 * 1024 * 1024, // 4M
// 最多可上传几个文件,默认为 100
maxNumberOfFiles: 10,
// 超时时间,默认为 10 秒
timeout: 5 * 1000, // 5 秒
// 用户自定义上传图片
customUpload(file, insertFn) {
const data = new FormData();
data.append("file", file);
//这里写自己的接口
axios({
method: '',
url: '',
headers: { 'Content-Type': '' },
data: data
}).then((res) => {
const {url} = res;
insertFn(url);
}).catch(err => {
})
}
}
}
}
// 销毁 editor
useEffect(() => {
return () => {
if (editor == null) return
editor.destroy()
setEditor(null)
}
}, [editor])
const onChangeonChange = editor => {
let newHtml = editor.getHtml();
console.log(newHtml);
}
return (
<>
<div style={{ border: '1px solid #ccc', zIndex: 100 }}>
<Toolbar
editor={editor}
defaultConfig={toolbarConfig}
mode="default"
style={{ borderBottom: '1px solid #ccc' }}
/>
<Editor
defaultConfig={editorConfig}
value={html}
onCreated={setEditor}
onChange={editor => onChangeonChange(editor)}
mode="default"
style={{ height: '500px', overflowY: 'hidden' }}
/>
</div>
</>
)
}
export default MyEditor