React富文本編輯器Braft Editor學習使用筆記

官網:https://braft.margox.cn/

文檔地址:https://www.yuque.com/braft-editor/be/lzwpnr

1、安裝

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

# 使用yarn安裝
yarn add braft-editor

2、官方例子

import React from 'react'
// 引入編輯器組件
import BraftEditor from 'braft-editor'
// 引入編輯器樣式
import 'braft-editor/dist/index.css'

export default class EditorDemo extends React.Component {

    state = {
        // 創建一個空的editorState作爲初始值
        editorState: BraftEditor.createEditorState(null)
    }

    async componentDidMount () {
        // 假設此處從服務端獲取html格式的編輯器內容
        const htmlContent = await fetchEditorContent()
        // 使用BraftEditor.createEditorState將html字符串轉換爲編輯器需要的editorStat
        this.setState({
            editorState: BraftEditor.createEditorState(htmlContent)
        })
    }

    submitContent = async () => {
        // 在編輯器獲得焦點時按下ctrl+s會執行此方法
        // 編輯器內容提交到服務端之前,可直接調用editorState.toHTML()來獲取HTML格式的內容
        const htmlContent = this.state.editorState.toHTML()
        const result = await saveEditorContent(htmlContent)
    }

    handleEditorChange = (editorState) => {
        this.setState({ editorState })
    }

    render () {

        const { editorState } = this.state
        return (
            <div className="my-component">
                <BraftEditor
                    value={editorState}
                    onChange={this.handleEditorChange}
                    onSave={this.submitContent}
                />
            </div>
        )

    }

}

3、在項目中表單裏實際應用

1、定義
state={
     editorState: BraftEditor.createEditorState(null)
}
2、
<FormItem {...formItemLayout} label="報告內容">
                  {getFieldDecorator('rptcontent', {
                rules: [
                  {
                    required: true,
                    message: '請輸入報告介紹',
                  },
                ],
              })(<BraftEditor
                className="my-editor"
                placeholder="請輸入報告內容"
                imageControls={imageControls}
                excludeControls={excludeControls}
                style={{ border: '1px solid #d9d9d9' }}
                media={{ uploadFn: this.myUploadFn }}
              />)}
            </FormItem> 
3、
 /* 
**富文本上傳圖片
*/
  myUploadFn = (param) => {
    let formData = new FormData();
    formData.append('file', param.file);
    fetch('/api/common/upload', {
      method: 'POST', // or 'PUT'
      body: formData,
      headers: {
        'Blade-Auth': getToken()
      }
    }).then(res => res.json())
      .then(response => {
        //console.log('Success:', response)
        param.success({
          url: response.data.url
        })
      })
      .catch(error => {
        //console.error('Error:', error)
      });
  }
4、
 //設置表單內的富文本內容(轉換)
        this.props.form.setFieldsValue({
          pgcontent: BraftEditor.createEditorState(res.data.pgcontent),
        })
5、展示富文本內容
state = {
    outputHTML: ''
  }
 //設置
    dispatch({
      type: 'program/fetchDetail',
      payload: { id },
      callback: (res) => {
        //設置富文本內容
        this.setState({
          outputHTML: `${BraftEditor.createEditorState(res.data.pgcontent).toHTML()}`
        });
      }
    });
<FormItem {...editLable} label="活動內容" >
                  <div dangerouslySetInnerHTML={{ __html: outputHTML }}></div>
                </FormItem>

 4、美化輸出內容

// 在展示頁面引入css樣板文件
import 'braft-editor/dist/output.css'

// 給用於展示HTML內容的容器加上特定的className
<div className="braft-output-content" dangerouslySetInnerHTML={{__html: outputContent}}></div

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章