首页 > 技术文章 > BraftEditor的使用

wwj0418 2021-07-23 10:37 原文

因为自己使用的是存函数所以简单记录一下,因为官网上没有对存函数的试用,所以还是要用到onchange或者onBlur都可以来获取文本框中的值,但是又因为文本框返回的是函数,所以要转成标签格式

<BraftEditor value={content} onChange={async (val) => setContent(val.toHTML())} ></BraftEditor>

在利用useState来赋值

const [content, setContent] = useState()
//修改时显示
setContent(BraftEditor.createEditorState(values?.content))

提交的时候直接给值就可以了。
如果阁下使用的是非存函数组件请移步官网官网

具体使用

占时自定义只设计到图片自定义上传
讲下具体流程

  • 首先具体定义参数初始化内容
const [content, setContent] = useState(BraftEditor.createEditorState(null))

这里这样初始化也是考虑到图片上传是会出现getSelect undefined 的问题
后面就是在onChange事假中传的是editorState

<BraftEditor
              controls={controls}
              value={introduce}
              onChange={(editorState) => { setIntroduce(editorState) }}
              extendControls={extendControlsIntroduce}
            >

这里需要注意的就是,官网给的是类函数传值,
在这里插入图片描述
这里用useState不要带大括号,不然会有意想不到的错误,然后就是在处理图片上

const extendControlsContent: any = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: (
        <Upload
          accept="*"
          showUploadList={false}
          onChange={handleImageContentChange}
          action='http://127.0.0.1:9097/upload/image'
        >
          <button type="button" className="control-item button upload-button" data-title="插入图片">上传图片</button>
        </Upload>
      )
    }
  ]

这里我们依然用的是onChange事件

	const handleImageContentChange = (info: any) => {
    if (info?.file?.response?.message == "success") {
      setContent(ContentUtils.insertMedias(content, [{
        type: 'IMAGE',
        url: info?.file?.response?.url
      }]))
    }
  }

具体实现结果
在这里插入图片描述
下面附上我这个完整的form表单代码,供大家参考

import React, { useState, useEffect } from "react";
import { Card, DatePicker, Form, message, Upload } from "antd"
import BraftEditor from "braft-editor"
import "braft-editor/dist/index.css"
import ProForm, { ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { addArticle, updateArticle } from "@/services/api-type/api";
import { useLocation, history } from "umi";
import moment from "moment";
import { ContentUtils } from "braft-utils"

const UpdateForm: React.FC<any> = (props) => {
  const [form] = Form.useForm()
  const location: any = useLocation()
  const { ...values } = location.query?.values
  const [introduce, setIntroduce] = useState(BraftEditor.createEditorState(null))
  const [content, setContent] = useState(BraftEditor.createEditorState(null))

  //富选框参数
  const controls: any = ['undo', 'redo', 'separator',
    'font-size', 'line-height', 'letter-spacing', 'separator',
    'text-color', 'blod', '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',
    'clear', 'separator',
  ]

  useEffect(() => {
    if (values?.id) {
      setContent(BraftEditor.createEditorState(values?.content))
      setIntroduce(BraftEditor.createEditorState(values?.introduce))
    }
  }, [])
  const onFinish = async (val: any) => {
    if (values?.id) {
      val.id = values?.id
    }
    val.introduce = introduce.toHTML()
    val.content = content.toHTML()
    const hide = message.loading('正在更新');
    try {
      let response
      if (values?.id) {
        response = await updateArticle(val as API.ArticleListItem)
      } else if (!values?.id) {
        response = await addArticle(val as API.ArticleListItem)
      }
      if (response?.code === 10000) {
        hide()
        message.success('更新成功');
        history.goBack()
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试!');
    }
  }
  const handleImageContentChange = (info: any) => {
    if (info?.file?.response?.message == "success") {
      setContent(ContentUtils.insertMedias(content, [{
        type: 'IMAGE',
        url: info?.file?.response?.url
      }]))
    }
  }
  const handleImageIntroduceChange = (info: any) => {
    if (info?.file?.response?.message == "success") {
      setIntroduce(ContentUtils.insertMedias(introduce, [{
        type: 'IMAGE',
        url: info?.file?.response?.url
      }]))
    }
  }
  const extendControlsIntroduce: any = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: (
        <Upload
          accept="*"
          showUploadList={false}
          onChange={handleImageIntroduceChange}
          action='http://127.0.0.1:9097/upload/image'
        >
          <button type="button" className="control-item button upload-button" data-title="插入图片">上传图片</button>
        </Upload>
      )
    }
  ]

  const extendControlsContent: any = [
    {
      key: 'antd-uploader',
      type: 'component',
      component: (
        <Upload
          accept="*"
          showUploadList={false}
          onChange={handleImageContentChange}
          action='http://127.0.0.1:9097/upload/image'
        >
          <button type="button" className="control-item button upload-button" data-title="插入图片">上传图片</button>
        </Upload>
      )
    }
  ]

  return (
    <Card>
      <ProForm onFinish={onFinish} initialValues={{ ...values }} form={form}>
        <ProForm.Group>
          <ProFormText width="lg" name="title" label="标题" placeholder="请输入标题"></ProFormText>
          <ProFormSelect name="typeId" label="分类" placeholder="请选择文章分类"></ProFormSelect>
          <Form.Item
            name="create_at"
            label="创建日期"
            getValueFromEvent={(val: any) => { return val.valueOf() }}
            getValueProps={(val: any) => moment(val)}
          >
            <DatePicker
              defaultValue={values?.create_at ? moment(values?.create_at) : undefined}
              format="YYYY/MM/DD"
              placeholder="请输入创建日期">
            </DatePicker>
          </Form.Item>
        </ProForm.Group>
        <Card >
          <ProForm.Item
            label="文章简介"
          >
            <BraftEditor
              controls={controls}
              value={introduce}
              onChange={(editorState) => { setIntroduce(editorState) }}
              extendControls={extendControlsIntroduce}
            >

            </BraftEditor>
          </ProForm.Item>
        </Card>
        <Card >
          <ProForm.Item
            label="文章内容"
          >
            <BraftEditor
              value={content}
              controls={controls}
              onChange={(editorState) => { setContent(editorState) }}
              extendControls={extendControlsContent}
            ></BraftEditor>
          </ProForm.Item>
        </Card>
      </ProForm>
    </Card>
  )
}
export default UpdateForm

多嘴提一句,这里使用的是ProComponents组件,是根据antd封装的,使用antd组件中的form结果相同,不影响效果,还有就会这没有调节样式。就这些
本文连接点击
博主个人小博客:嘿嘿

推荐阅读