言慕 發表於 2020-2-24 13:45:00

React 中使用富文本编辑器 Braft Editor ,并集成上传图片功能

<p>Braft Editor 是基于draft-js开发的富文本编辑器,适用于 React 框架。</p>
<h2 id="1-安装">1. 安装</h2>
<h4 id="使用npm">使用npm</h4>
<pre><code>npm install braft-editor --save
</code></pre>
<h4 id="使用yarn">使用yarn</h4>
<pre><code>yarn add braft-editor
</code></pre>
<h2 id="2-基本使用">2. 基本使用</h2>
<pre><code>import React, { Component } from 'react'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'

export default class Main extends Component {

state = {
    editorState: BraftEditor.createEditorState('&lt;p&gt;初始值&lt;/p&gt;'), // 设置编辑器初始内容
    outputHTML: '&lt;p&gt;&lt;/p&gt;' // 编辑器输出内容
}

componentDidMount () {
    this.setState({
      editorState: BraftEditor.createEditorState('&lt;p&gt;hello,&lt;b&gt;world!&lt;/b&gt;&lt;p&gt;')
    })
}

handleChange = (editorState) =&gt; {
    this.setState({
      editorState: editorState,
      outputHTML: editorState.toHTML()
    }, () =&gt; {
      console.log(editorState)
      console.log(this.state.outputHTML)
    })
}

render () {
    const { editorState, outputHTML } = this.state

    return (
      &lt;div&gt;
      &lt;div className="editor-wrapper"&gt;
          &lt;BraftEditor
            value={editorState}
            onChange={this.handleChange}
          /&gt;
      &lt;/div&gt;
      &lt;/div&gt;
    )
}
}
</code></pre>
<h2 id="2-自定义内置控件">2. 自定义内置控件</h2>
<p>Braft Editor使用 controls 属性指定需要展示的控件;使用contentStyle调整编辑区域的高度。</p>
<pre><code>render () {
      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'
    ]

    return (
      &lt;div className="editor-wrapper"&gt;
      &lt;BraftEditor
          controls={controls}
          contentStyle={{height: 210, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)'}}
      /&gt;
      &lt;/div&gt;
    )

}
</code></pre>
<h2 id="3-集成-ant-design-上传组件">3. 集成 Ant Design 上传组件</h2>
<p>Braft Editor上传图片会默认转成base64, 下面将使用Ant Design 的上传组件改成上传到服务器的方法:</p>
<br>
<ul>
<li>使用ContentUtils来将上传后的图片插入到编辑器,安装:</li>
</ul>
<pre><code>yarn add braft-utils
</code></pre>
<ul>
<li>使用component类型的extendControls将Upload组件集成到编辑器工具栏</li>
</ul>
<pre><code>import React, { Component } from 'react'
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'

export default class Main extends Component {

state = {
    editorState: BraftEditor.createEditorState(null)
}

componentDidMount () {
    this.setState({
      editorState: BraftEditor.createEditorState('&lt;p&gt;hello,&lt;b&gt;world!&lt;/b&gt;&lt;p&gt;')
    })
}

onOk = () =&gt; {
    this.props.form.validateFields((err, fieldsValue) =&gt; {
      if (!err) {
      console.log(fieldsValue)
      }
    })
}

beforeUpload = file =&gt; {
    this.props.form.setFieldsValue({
      content: ContentUtils.insertMedias(this.props.form.getFieldValue('content'), [{
      type: 'IMAGE',
      url: imgUrl, // imgUrl 为上传成功后 后台返回的url地址
      }])
    return false
}


render () {
   const {
      form: { getFieldDecorator },
    } = this.props

    const { editorState } = this.state

    const formItemLayout = {
      labelCol: {
      sm: { span: 4 },
      },
      wrapperCol: {
      sm: { span: 20 },
      },
    }


    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 extendControls = [
      {
      key: 'antd-uploader',
      type: 'component',
      component: (
          &lt;Upload
            accept="image/*"
            showUploadList={false}
            beforeUpload={this.beforeUpload}
          &gt;
            {/* 这里的按钮最好加上type="button",以避免在表单容器中触发表单提交,用Antd的Button组件则无需如此 */}
            &lt;button type="button" className="control-item button upload-button" data-title="插入图片"&gt;
            &lt;Icon type="picture" theme="filled" /&gt;
            &lt;/button&gt;
          &lt;/Upload&gt;
      )
      }
    ]

    return (
      &lt;div&gt;
      &lt;div className="editor-wrapper"&gt;
          &lt;Form {...formItemLayout}&gt;
            &lt;Form.Item label="标题"&gt;
            {getFieldDecorator(`title`, {
                initialValue: '',
                rules: [{ required: true, message: '请输入标题' }],
            })(
                &lt;Input placeholder="请输入" allowClear style={{ width: 300 }} /&gt;
            )}
            &lt;/Form.Item&gt;
            &lt;Form.Item label="内容"&gt;
            {getFieldDecorator(`content`, {
                validateTrigger: 'onBlur',
                initialValue: editorState,
                rules: [{ required: true, message: '请输入内容' }],
            })(
                &lt;BraftEditor
                  className={styles.editorStyle}
                  contentStyle={{ height: 160, boxShadow: 'inset 0 1px 3px rgba(0,0,0,.1)' }}
                  controls={controls}
                  extendControls={extendControls}
                  placeholder="请输入正文内容"
                /&gt;
            )}
            &lt;/Form.Item&gt;
            &lt;Form.Item&gt;
            &lt;Button type="primary" onClick={this.onOk}&gt;
                确定
            &lt;/Button&gt;
            &lt;/Form.Item&gt;
          &lt;/Form&gt;

      &lt;/div&gt;
      &lt;/div&gt;
    )
}
}
</code></pre><br><br>
来源:https://www.cnblogs.com/cckui/p/12356657.html
頁: [1]
查看完整版本: React 中使用富文本编辑器 Braft Editor ,并集成上传图片功能