react中使用富文本框BraftEditor限制图片大小

1、参考文档

brafteditor:安装和使用 (yuque.com)

# 使用npm安装
npm install braft-editor --save

# 使用yarn安装
yarn add braft-editor

2、使用事例

2.1引用BraftEditor
import BraftEditor from 'braft-editor';
2.2页面渲染

在render()函数中

 <BraftEditor
   id='braft'
   className="my-editor"
   controls={controls}
   onChange={this.handleEditorChange}
   media={{
   validateFn: this.myValidateFn
   }}
   style={{ border: '1px solid #d9d9d9',width:'100%' }}
   placeholder="请输入指南内容"
  />
2.3controls指定编辑器工具栏的控件列表

默认值如下:

const controls=[
    'undo', 'redo', 'separator',
    'font-size', 'line-height', 'letter-spacing', 'separator',
    'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
    'superscript', 'subscript', 'remove-styles', 'emoji',  'separator', 'text-indent', 'text-align', 'separator',
    'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
    'link', 'separator', 'hr', 'separator',
    'media', 'separator',
    'clear'
]

如果要加入自定义的控件以下是一个例子

const controls=[
    {
        key: 'custom-upload', // 控件的唯一标识
        title: '上传文件', // 控件的标题
        text: '上传文件', // 控件显示的文本
        onClick: this.handleCustomUpload // 点击事件处理函数
      }
  
]
2.4限制从本地上传的图片大小

media.validateFn

该函数用于校验从本地选择的媒体文件,可以是一个普通函数,也可以是一个Promise对象,校验不通过的媒体文件将不会被添加到媒体库中。

 myValidateFn = (file) => new Promise((resolve, reject) => {
      const maxWidth = 1200; // 最大宽度限制
      const maxHeight = 1200; // 最大高度限制

      const img = new Image();
      img.src = window.URL.createObjectURL(file);

      img.onload = function() {
        const {width} = img;
        const {height} = img;

        if (file.size < 1024 * 200 && width < maxWidth && height < maxHeight) {
          resolve();
        } else {
          let errorMessage = '';
          if (file.size >= 1024 * 200) {
            errorMessage += '图片大小超过200KB,';
          }
          if (width >= maxWidth) {
            errorMessage += '图片宽度超过1200,';
          }
          if (height >= maxHeight) {
            errorMessage += '图片高度超过1200,';
          }
          errorMessage += '不能上传';

          message.error(errorMessage);
          reject();
        }
      };
    });

3、实现效果

  • 12
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值