React中使用Vditor自定义图片详解


Posted in Javascript onDecember 25, 2020

安装

npm install vditor -s

引用

导入依赖包

import Vditor from "vditor";

导入样式

import "vditor/src/assets/scss/index.scss";

使用示例

export default class Vditor extends Component {
 constructor(props) {
   super(props);
   this.state = {
    editValue: ""
   };
 }
 componentDidMount = () => {
  //组件挂载完成之后调用 注意一定要在组件挂载完成之后调用 否则会找不到注入的DOM
  this.createVidtor({ value: this.state.editValue });
 }
 //创建编辑器 下面会详解
 createVidtor = params => {
   let { value } = params;
   value = value ? value : " ";
   let that = this;
   const vditor = new Vditor("vditor", {
     height: 800,
     mode: "ir", //及时渲染模式
     placeholder: "React Vditor",
     toolbar: [
       "emoji",
       "headings",
       "bold",
       "italic",
       "strike",
       "link",
       "|",
       "list",
       "ordered-list",
       "check",
       "outdent",
       "indent",
       "|",
       "quote",
       "line",
       "code",
       "inline-code",
       "insert-before",
       "insert-after",
       "|",
       "upload",
       "table",
       "|",
       "undo",
       "redo",
       "|",
       "fullscreen",
       "edit-mode",
       {
         name: "more",
         toolbar: [
           "both",
           "code-theme",
           "content-theme",
           "export",
           "outline",
           "preview",
           "devtools",
           "info",
           "help"
         ]
       },
       "|",
       {
         hotkey: "⌘-S",
         name: "save",
         tipPosition: "s",
         tip: "保存",
         className: "right",
         icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/save.svg'/>`,
         click() {
           that.saveDoc();
         }
       },
       {
         hotkey: "",
         name: "publish",
         tipPosition: "s",
         tip: "发布文章",
         className: "right",
         icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/publish.svg'/>`,
         click() {
           that.publishDoc();
         }
       }
     ],
     after() {
       vditor.setValue(value);
     },
     blur() {
       that.saveDoc();
     },
     upload: {
       accept: "image/*",
       multiple: false,
       filename(name) {
         return name
           .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
           .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
           .replace("/\\s/g", "");
       },
       handler(files) {
         function callback(path) {
           let name = files[0] && files[0].name;
           let succFileText = "";
           if (vditor && vditor.vditor.currentMode === "wysiwyg") {
             succFileText += `\n <img alt=${name} src="${path}">`;
           } else {
             succFileText += ` \n![${name}](${path})`;
           }
           document.execCommand("insertHTML", false, succFileText);
         }
         that.handleImageUpload(files, callback);
       },
       url(files) {
         that.handleImageUpload(files);
       }
     }
   });
   this.vditor = vditor;
   return vditor;
 };
 //首先需要在render里面注入DOM,可自定义注入DOM的ID,初始化编辑器的时候使用自定义的ID即可
 render() {
  <div className="editorWrap">
    <div id="vditor" />
  </div>
 }
}

示例:

React中使用Vditor自定义图片详解

功能使用

新建对象

const vditor = new Vditor("vditor", ...option);

新建对象时第一个参数ID,要对应上再render里面注入的ID

option参数

tip:只列举一下常用参数,其他的参数请参照 官方API

参数 说明
height 配置编辑器高度
mode 编辑器模式 wysiwyg:所见即所得2 ir:及时渲染 sv:分屏模式
placeholder 占位符
toolbar 工具栏

Tip:如果要自定义工具栏的话,一定要加上默认的工具栏,不然只展示自定义的了

默认工具栏

tip:此为源码里面copy 不用更改可直接使用,官方已定义好了快捷键和功能

toolbar: [
      "emoji",
      "headings",
      "bold",
      "italic",
      "strike",
      "link",
      "|",
      "list",
      "ordered-list",
      "check",
      "outdent",
      "indent",
      "|",
      "quote",
      "line",
      "code",
      "inline-code",
      "insert-before",
      "insert-after",
      "|",
      "upload",
      "record",
      "table",
      "|",
      "undo",
      "redo",
      "|",
      "fullscreen",
      "edit-mode",
      {
        name: "more",
        toolbar: [
          "both",
          "code-theme",
          "content-theme",
          "export",
          "outline",
          "preview",
          "devtools",
          "info",
          "help",
        ],
      }]

对应工具栏展示:

React中使用Vditor自定义图片详解

自定义按钮

let that = this;
const vditor = new Vditor("vditor", {
  toolbar: [
    {
      hotkey: "⌘-S",
      name: "save",
      tipPosition: "s",
      tip: "保存",
      className: "right",
      icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/save.svg'/>`,
      click() {
        that.saveDoc();
      }
    },
    {
      hotkey: "",
      name: "publish",
      tipPosition: "s",
      tip: "发布文章",
      className: "right",
      icon: `<img style="height: 16px" src='https://img.58cdn.com.cn/escstatic/docs/imgUpload/idocs/publish.svg'/>`,
      click() {
        that.publishDoc();
      }
    }
  ]
});
//tip:在调用本类封装的方法时提前把this赋值给其他方法内的变量,在Vditor内部改变了this指向

参数 说明
hotkey 热键配置
name 功能区分(唯一性)
tip 悬浮提示
className UI展示 right靠右
icon 按钮图标
click 点击事件

示例:

React中使用Vditor自定义图片详解

获取值

saveDoc = () => {
 //在初始化时已经把vditor赋值到this对象上 可直接通过getValue方法获取当前编辑器的值
  let mdValue = this.vditor && this.vditor.getValue();
 //获取完值业务保存就行 这里不再详细写本人的保存方法了
 ...
}

赋值

let { value } = params;
value = value ? value : " ";
//如果是空值的话 最好给一个空格 以免编辑器初始化时报错
const vditor = new Vditor("vditor", {
 // value: value,
 after() {
   vditor.setValue(value);
 }
});
//tip:虽说官方也提供value直接赋值 但是在React里面不生效,就需要在after里面去调用setValue来完成赋值

自定义图片上传

const vditor = new Vditor("vditor", {
 upload: {
   accept: "image/*",
   multiple: false,
   filename(name) {
     return name
       .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, "")
       .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, "")
       .replace("/\\s/g", "");
   },
   handler(files) {
     function callback(path) {
       let name = files[0] && files[0].name;
       let succFileText = "";
       if (vditor && vditor.vditor.currentMode === "wysiwyg") {
         succFileText += `\n <img alt=${name} src="${path}">`;
       } else {
         succFileText += ` \n![${name}](${path})`;
       }
       document.execCommand("insertHTML", false, succFileText);
     }
     that.handleImageUpload(files, callback);
   },
   url(files, callback) {
     that.handleImageUpload(files, callback);
   }
 }
});
//此接口里面调用的是自己的图片上传 业务方自行实现
handleImageUpload = (file, callback) => {
  const reader = new FileReader();
  let formdata = new FormData();
  formdata.append("files", file[0]);
  reader.onload = () => {
    // setTimeout 模拟异步上传图片
    // 当异步上传获取图片地址后,执行callback回调(参数为imageUrl字符串),即可将图片地址写入markdown
    new Promise(resolve => {
      this.props.dispatch({
        type: "docManager/imageUpload",
        payload: { resolve, username: myInfo.userId, formdata }
      });
    }).then(res => {
      let imgurl = res.result.path;
      callback(imgurl);
    });
  };
  reader.readAsDataURL(file[0]);
};

参数 说明
accept 接收文件类型(我这边只做了图片上传)
multiple 是否多选
filename 格式化文件名
handler 点击数触发方法
url 配置此方法时可实现图片粘贴并上传

React中使用Vditor自定义图片详解

上传完成后接口返回的CDN地址

React中使用Vditor自定义图片详解

上传完成后处理

handler(files) {
  function callback(path) {
    let name = files[0] && files[0].name;
    let succFileText = "";
    //上传完成获取当前编辑器模式 根据不同模式拼接不同的展示标签
    if (vditor && vditor.vditor.currentMode === "wysiwyg") {
      succFileText += `\n <img alt=${name} src="${path}">`;
    } else {
      succFileText += ` \n![${name}](${path})`;
    }
    //拼接完直接插入到鼠标选中位置
    document.execCommand("insertHTML", false, succFileText);
  }
  that.handleImageUpload(files, callback);
}

React中使用Vditor自定义图片详解

总结

以上是本人在接入vditor编辑器是的一些使用总结,更多相关React Vditor内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Javascript 相关文章推荐
权威JavaScript 中的内存泄露模式
Aug 13 Javascript
基于jQuery判断两个元素是否有重叠部分的代码
Jul 25 Javascript
jQuery定义插件的方法
Dec 18 Javascript
Bootstrap进度条学习使用
Feb 09 Javascript
使用jQuery监听扫码枪输入并禁止手动输入的实现方法(推荐)
Mar 21 jQuery
基于rem的移动端响应式适配方案(详解)
Jul 07 Javascript
JS返回顶部实例代码
Aug 09 Javascript
利用es6 new.target来对模拟抽象类的方法
May 10 Javascript
微信小程序实现按字母排列选择城市功能
Nov 25 Javascript
js实现鼠标点击飘爱心效果
Aug 19 Javascript
JS+Canvas实现五子棋游戏
Aug 26 Javascript
JavaScript arguments.callee作用及替换方案详解
Sep 02 Javascript
基于vue+echarts数据可视化大屏展示的实现
Dec 25 #Vue.js
vue3使用vue-count-to组件的实现
Dec 25 #Vue.js
js+for循环实现字符串自动转义的代码(把后面的字符替换前面的字符)
Dec 24 #Javascript
Javascript 模拟mvc实现点餐程序案例详解
Dec 24 #Javascript
vant时间控件使用方法详解
Dec 24 #Javascript
基于Vant UI框架实现时间段选择器
Dec 24 #Javascript
原生jQuery实现只显示年份下拉框
Dec 24 #jQuery
You might like
PHP 和 HTML
2006/10/09 PHP
Win2003服务器安全加固设置--进一步提高服务器安全性
2007/05/23 PHP
PHP合并数组+与array_merge的区别分析
2010/08/01 PHP
百度ping方法使用示例 自动ping百度
2014/01/26 PHP
Jquery选择子控件&quot;大于号&quot;和&quot; &quot;区别介绍及使用示例
2013/06/25 Javascript
jquery1.10给新增元素绑定事件的方法
2014/03/06 Javascript
jQuery EasyUI常用数据验证汇总
2016/09/18 Javascript
移动开发之自适应手机屏幕宽度
2016/11/23 Javascript
ionic3实战教程之随机布局瀑布流的实现方法
2017/12/28 Javascript
解决layui中table异步数据请求不支持自定义返回数据格式的问题
2018/08/19 Javascript
clipboard在vue中的使用的方法示例
2018/10/19 Javascript
layui自定义插件citySelect实现省市区三级联动选择
2019/07/26 Javascript
antd-mobile ListView长列表的数据更新遇到的坑
2020/04/08 Javascript
JavaScript闭包原理与用法学习笔记
2020/05/29 Javascript
JavaScript实现多文件下载方法解析
2020/08/07 Javascript
js实现微信聊天界面
2020/08/09 Javascript
three.js如何实现3D动态文字效果
2021/03/03 Javascript
[01:14:10]2014 DOTA2国际邀请赛中国区预选赛 SPD-GAMING VS Orenda
2014/05/22 DOTA
python socket 超时设置 errno 10054
2014/07/01 Python
python实现的简单抽奖系统实例
2015/05/22 Python
总结用Pdb库调试Python的方式及常用的命令
2016/08/18 Python
K-means聚类算法介绍与利用python实现的代码示例
2017/11/13 Python
Pytorch的mean和std调查实例
2020/01/02 Python
python PIL/cv2/base64相互转换实例
2020/01/09 Python
彻底搞懂python 迭代器和生成器
2020/09/07 Python
利用html5 canvas破解简单验证码及getImageData接口应用
2013/01/25 HTML / CSS
video.js支持m3u8格式直播的实现示例
2020/05/20 HTML / CSS
美国健康和保健平台:healtop
2020/07/02 全球购物
幼师求职自荐信范文
2014/01/26 职场文书
校园会短篇的广播稿
2014/10/21 职场文书
2014年社区卫生工作总结
2014/12/18 职场文书
公司地址变更通知
2015/04/25 职场文书
婚礼父母致辞
2015/07/28 职场文书
Python自动化测试PO模型封装过程详解
2021/06/22 Python
解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题
2021/07/01 Java/Android
python中Matplotlib绘制直线的实例代码
2021/07/04 Python