具体实现思路: 使用原生粘贴方法获取到粘贴版的内容然后调用富文本根据光标插入内容的方法
使用到的知识点以及api:
1、调用wangeditor富文本根据光标插入内容的api:
this.editorExample.current.editor.cmd.do(‘insertHTML’, <img src=${res.imageUrl} />
)
相关链接
2、event.clipboardData || event.originalEvent.clipboardData
相关链接 (阮大大 yyds)
componentDidMount = () => {
document.getElementById('WEditor-view').addEventListener('paste', this.pasteDataEvent)
}
pasteDataEvent = event => {
event.preventDefault()
if (event.clipboardData || event.originalEvent) {
//某些chrome版本使用的是event.originalEvent
let clipboardData = event.clipboardData || event.originalEvent.clipboardData
if (clipboardData.items) {
// for chrome
let items = clipboardData.items,
len = items.length,
blob = null
for (let i = 0; i < len; i++) {
console.log(items[i])
if (items[i].type.indexOf('image') !== -1) {
//getAsFile() 此方法只是living standard firefox ie11 并不支持
blob = items[i].getAsFile()
this.addImg(blob, 'No') // 自定义上传到oss或是七牛云图片的方法
}
}
}
}
}
// 上传图片的方法
addImg = async (event, val) => {
const file = val === 'No' ? event : event.currentTarget.files[0]
if (!file || !this.state.listData.length) return
uploadImage(file).then(res => {
// 上传成功之后调用富文本的方法插入到光标的位置
this.editorExample.current.editor.cmd.do('insertHTML', `<img src=${res.imageUrl} />`)
document.getElementById('uploadfile').value = null
})
}
// 卸载富文本以及移除事件
componentWillUnmount = () => {
if (this.editorExample.current) {
this.editorExample.current.editor.destroy()
}
document.getElementById('WEditor-view').removeEventListener('paste', this.pasteDataEvent)
}
资料链接:
https://www.cnblogs.com/heihei-haha/p/7879611.html
https://developer.mozilla.org/zh-CN/docs/Web/API/Clipboard
以上就是 react 从剪切板里粘贴图片并使用WEditor富文本展示的所有代码了 欢迎各位大佬指点