当前位置: 首页 > 工具软件 > BRAFT > 使用案例 >

react-braft-editor富文本编辑器

祁正浩
2023-12-01

目录

一、创建index.js

二、less文件

三、页面中引用组件

四、编辑器oss图片上传


一、创建index.js

import BraftEditor from 'braft-editor'
import React from 'react'
import 'braft-editor/dist/index.css'
import { useEffect, useState } from 'react'
import { message } from 'antd'
import './index.less'

/**
 * @typedef Props
 * @extends React.Props
 *
 */

/**
 * 提供支持 ProForm 访问的 BraftEditor 包装
 * @type React.Component<Props>
 */
const Editor = (props) => {
  const { name, value, onChange, handleImage, ...editorProps } = props
  const [editorState, setEditorState] = useState(
    BraftEditor.createEditorState(value)
  )

  const onEditorChange = (state) => {
    setEditorState(state)
    if (onChange) {
      onChange(state.toHTML())
    }
  }
  const excludeControls = ['code']
  const validateFn = (file) => {
    if (!/image\/\w+/.test(file.type)) {
      message.warning('请选择图片格式的文件上传', 2)
      return false
    } else if (file.size > 1024 * 1024 * 10) {
      message.warning('每张图片的大小不能超过10M', 2)
      return false
    }
    return true
  }
  const media = {
    image: true,
    uploadFn: handleImage,
    validateFn: validateFn,
    accepts: {
      image:
        'images/png,images/jpg,images/jpeg,images/gif,images/webp,images/apng,images/svg',
      video: false,
      audio: false
    }
  }

  useEffect(() => {
    if (editorState.toHTML() !== value) {
      setEditorState(BraftEditor.createEditorState(value))
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [value])

  return (
    <div className='editor'>
      <BraftEditor
        value={editorState}
        onChange={onEditorChange}
        excludeControls={excludeControls}
        media={media}
        {...editorProps}
      />
    </div>
  )
}

export default Editor

二、less文件

.editor {
    border: solid 1px @black-auxiliary;

    &:hover {
        border: solid 1px @black-auxiliary
    }

   
}
.pull-left {
    display: none;
}

三、页面中引用组件

import Editor from "../../../components/Editor";


//引用组件 oss上传图片的回调
<Editor handleImage={(param) => this.store.handleImage(param)}/>

四、编辑器oss图片上传

  handleImage(param) {
    console.log(param);
    request({
      url: "oss上传api",
      method: "GET",
      // data: { type: 19 }
    })
      .then((policyRes) => {
        //上传需要相关数据
        console.log(policyRes);
        var {
          accessid,
          callback,
          dir,
          expire,
          host,
          policy,
          signature,
          prefix,
        } = policyRes.data;
        var file = param.file;
        let formData = new FormData();
        let md5 =
          utils.getRandomString() + "." + param.file.name.split(".").pop();
        formData.append("name", param.file.name);
        formData.append("key", encodeURI(dir + prefix + md5));
        formData.append("policy", policy);
        formData.append("OSSAccessKeyId", accessid);
        formData.append("success_action_status", "200");
        formData.append("callback", callback);
        formData.append("signature", signature);
        formData.append("file", file);
        //开始上传
        request({ url: host, method: "post", data: formData })
          .then((uploadRes) => {
            if (uploadRes.code === constant.SUCCESS_CODE) {
              const imgUrl = uploadRes.filename;
              const successFn = (imgUrl) => {
                console.log(imgUrl);
                // 假设服务端直接返回文件上传后的地址
                // 上传成功后调用param.success并传入上传后的文件地址
                param.success({
                  // url: utils.pictureThumb(imgUrl, true, 1200, false, true),
                  url: "***" + imgUrl,
                });
              };
              successFn(imgUrl);
            } else {
              stores.Frame.error(uploadRes.message);
            }
          })
          .catch((uploadErr) => {
            stores.Frame.error(uploadErr.message);
          });
      })
      .catch((err) => {
        stores.Frame.error(errs.message);
      });
  }

 类似资料: