-
安装包
npm install @wangeditor/editor --save
npm install @wangeditor/editor-for-react --save
-
组件引入
import { error, success } from '@/utils/common'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import '@wangeditor/editor/dist/css/style.css'
import { Button, Input, Modal } from 'antd'
import React, { useEffect, useMemo, useState } from 'react'
function MyEditor({defaultHtml, editorDisable, articleId}) {
// editor 实例
const [editor, setEditor] = useState(null) // JS 语法
// 编辑器内容
const [html, setHtml] = useState(defaultHtml)
// 模拟 ajax 请求,异步设置 html
useEffect(() => {
if (articleId) {
// setTimeout(() => {
setHtml(defaultHtml)
// }, 1500)
}
}, [articleId])
// 工具栏配置
const toolbarConfig = {
excludeKeys: [
'insertVideo', // 插入网络视频
'uploadVideo', // 上传视频
'editVideoSize', // 修改视频尺寸
'group-video',
],
} // JS 语法
// 编辑器配置
const editorConfig = useMemo(
() => ({
// JS 语法
placeholder: '请输入内容...',
readOnly: editorDisable,
MENU_CONF: {
uploadImage: {
server: `/upload`,
// form-data fieldName ,默认值 'wangeditor-uploaded-image'
fieldName: 'file',
// 单个文件的最大体积限制,默认为 2M
maxFileSize: 4 * 1024 * 1024, // 4M
// 最多可上传几个文件,默认为 100
maxNumberOfFiles: 10,
// 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
allowedFileTypes: ['image/*'],
// 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
// meta: {
// token: 'xxx',
// otherKey: 'yyy',
// },
// 将 meta 拼接到 url 参数中,默认 false
metaWithUrl: false,
// 自定义增加 http header
headers: {
'Token': localStorage.getItem('token') || '',
},
// 跨域是否传递 cookie ,默认为 false
withCredentials: true,
// 超时时间,默认为 10 秒
timeout: 5 * 1000, // 5 秒
// 小于该值就插入 base64 格式(而不上传),默认为 0
base64LimitSize: 5 * 1024, // 5kb
// 用户自定义上传图片
// customUpload(file, insertFn) {
// const data = new FormData()
// data.append('file', file) // file 即选中的文件 主要就是这个传的参数---看接口要携带什么参数{ key :value}
// const hide = message.loading('上传中...', 0)
// // 这里写自己的接口
// server
// .uploadImage(data)
// .then(res => {
// insertFn(res.data[0]) // 插入图片,看返回的数据是什么
// hide()
// })
// .catch(err => {
// console.log(err)
// hide()
// })
// },
},
},
}),
[editorDisable],
)
// 及时销毁 editor ,重要!
useEffect(
() => () => {
if (editor == null) return
editor.destroy()
setEditor(null)
},
[editor],
)
return (
<div>
<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={editorChange}
mode="default"
style={{ height: '600px', overflowY: 'hidden' }}
/>
</div>
{/* <div style={{ marginTop: '15px' }}>{html}</div> */}
</div>
)
}
export default MyEditor