React rich text component react-lz-editor use

1. React-lz-editor official website address

https://github.com/leejaen/react-lz-editor

2. Introduction

npm install react-lz-editor --save
OR
yarn add react-lz-editor

3. Introduction to use in the project

The following is the demo of the official website. I made changes and instructions in it mainly when the file was uploaded.

import React from 'react';
import ReactDOM from 'react-dom';
import LzEditor from 'react-lz-editor'
import OSSUploaderFile from '../../utils/oss-uploader';
import findIndex from 'lodash/findIndex';
import uniqBy from 'lodash/uniqBy';

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      htmlContent: `<h1>Yankees, Peeking at the Red Sox, Will Soon Get an Eyeful</h1>
                <p>Whenever Girardi stole a glance, there was rarely any good news for the Yankees. While Girardi’s charges were clawing their way to a split of their four-game series against the formidable Indians, the Boston Red Sox were plowing past the rebuilding Chicago White Sox, sweeping four games at Fenway Park.</p>`,
      markdownContent: "## HEAD 2 \n markdown examples \n ``` welcome ```",
      fileList: []
    }
    this.receiveHtml=this.receiveHtml.bind(this);
  }
  receiveHtml(content) {
    console.log("recieved HTML content", content);
    this.setState({responseList:[]});
  }

 //这里是处理上传成功后数据集合处理 给fileList赋值的 这里可以看一下 这个是官网代码中实现的 核心部分
 handleChange = (changedValue) => {
    let currFileList = changedValue.fileList;
    // this.setState({ fileList: changedValue.fileList });
    console.error(JSON.stringify(changedValue));
    currFileList = currFileList.filter(f => (!f.length));
    // eslint-disable-next-line consistent-return
    currFileList = currFileList.map((file) => {
      if (file.response) {
        // 组件会将 file.url 作为链接进行展示
        // eslint-disable-next-line no-param-reassign
        file.url = file.response.url;
      }
      if (!file.length) {
        return file;
      }
    });
    const that = this;
    currFileList = currFileList.filter((file) => {
      // eslint-disable-next-line no-bitwise
      const hasNoExistCurrFileInUploadedList = !~findIndex(
        that.state.fileList, item => item.name === file.name,
      );
      if (hasNoExistCurrFileInUploadedList) {
        if (!!that.props.isMultiple === true) {
          that.state.fileList.push(file);
        } else {
          that.state.fileList = [file];
        }
      }
      return !!file.response || (!!file.url && file.status === 'done') || file.status === 'uploading';
    });
    currFileList = uniqBy(currFileList, 'name');
    if (!!currFileList && currFileList.length !== 0) {
      this.setState({ fileList: currFileList });
    }
    that.forceUpdate();
  };

  customRequest = ({
    file,
    onError,
    onSuccess,
  }) => {
    //这里是封装的oss图片上传网络请求
    OSSUploaderFile(file, onSuccess, onError);
  };

  render() {
    let policy = "";
    //这里主要的操作都在这里实现 可以查看https://ant.design/components/upload-cn/的配置
    const uploadProps = {
      //上传的文件内容变化触发
      onChange: this.handleChange ,
      listType: 'picture',
      //上传图片的集合
      fileList: this.state.fileList,
      //这个负责图片的上传 上传成功自动触发onChange 这里我使用的是阿里的oss 需要集成oss
      customRequest: this.customRequest,
      multiple: true,
      showUploadList: true
    }
    return (
      <div>
        <div>Editor demo 1 (use default html format ):
        </div>
        <LzEditor active={true} importContent={this.state.htmlContent} cbReceiver={this.receiveHtml} uploadProps={uploadProps}
        lang="en"/>
        <br/>
        <div>Editor demo 2 (use markdown format ):
        </div>
        <LzEditor
          active={true}
          importContent={this.state.markdownContent}
          cbReceiver={this.receiveMarkdown}
          image={false}
          video={false}
          audio={false}
          convertFormat="markdown"/>
      </div>
    );
  }
}

ReactDOM.render(
  <Test/>, document.getElementById('test'));

Four, oss upload tools

import OSS from 'ali-oss';
import {} from 'lodash';

const ossclient = new OSS({
  region: '',
  accessKeyId: '',
  accessKeySecret: '',
  stsToken: '',
  bucket: '',
});


function buildFileName(postfix) {
  return new Date().getTime() + postfix;
}


function OSSUploaderFile(file, onSucess, onError) {
  console.error(file);
  const index = file.name.lastIndexOf('.');

  if (index === -1) {
    return onError('file error.');
  }
  const postfix = file.name.substr(index);

  ossclient.put(buildFileName(postfix), file)
    .then((ret) => {
      onSucess(ret, file);
    })
    .catch(onError);
}


export default OSSUploaderFile;

 

Guess you like

Origin blog.csdn.net/weixin_39706415/article/details/93972133
Recommended