react 从剪切板里粘贴图片并使用WEditor富文本展示

具体实现思路: 使用原生粘贴方法获取到粘贴版的内容然后调用富文本根据光标插入内容的方法

使用到的知识点以及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富文本展示的所有代码了 欢迎各位大佬指点

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值