使用antd+braft-editor+braft-extensions創建帶有富文本編輯器的表單

braft-editor 富文本編輯器

最近項目中需要使用富文本編輯器,本身項目是基於react+antd 進行開發的,對比常用的富文本編輯器,發現braft-editor和antd的form表單驗證更配。記錄一下開發過程,共勉。

常見的開源富文本編輯器比較

Braft Editor 一個基於darft-js開發的Web富文本編輯器,使用參考:

1、使用文檔
2、在線演示
3、github
4、表格擴展

代碼

import './index.less';
import React from 'react';
import {Card, Form, Input, Row, Col, Select, Button, Upload, Icon, message} from 'antd';
import 'braft-editor/dist/index.css';
import 'braft-extensions/dist/table.css';
import BraftEditor from 'braft-editor';
import Table from 'braft-extensions/dist/table';
import axios from 'axios';


const {Item} = Form;
const {Option} = Select;
export default class Demo extends React.Component{

    constructor(props) {
        super(props);
        this.state ={
            isEdit:false
        };
    }


    //創建任務
    handleAddSubmit = () => {
        this.addFormData.props.form.validateFields((err, value) => {
            if (!err) {
                let softFunction = [];
                value.softFunction.map((item)=>(softFunction.push(item.label)));
                const param = {
                    ...value,
                    scene:value.scene.toHTML(),
                    attachment:value.attachment?value.attachment.file.response?
                        value.attachment.file.response.data:null:null,
                    softFunction:softFunction.join(","),
                    projectCategory:value.projectCategory.label,
                };
                axios.post('https://www.easy-mock.com/mock/5bfbf83591ea222a361d8316/rich/task',
                    {param}).then(res=>{
                        console.log(res)
                })
            }
        })
    };
    render() {
        const {isEdit} = this.state;
        return (
            <Card
                extra={
                    <Button
                        onClick={isEdit ? null : this.handleAddSubmit}
                        type={"primary"}>
                        保存
                    </Button>}
                title={'創建任務'}>
                {isEdit ? null :
                    <AddForm
                        wrappedComponentRef={(formData) => this.addFormData = formData}
                    />}
            </Card>
        );
    }

}

/**
 * 創建任務的表單
 */
class AddForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            scene: '<p></p>',
            fileList: []
        };
    }


    componentDidMount() {
        BraftEditor.use(Table());
        this.props.form.setFieldsValue({
            scene: BraftEditor.createEditorState("<p></p>")
        })
    }

    beforeUpload = (file) => {
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
            message.error('附件最多不超過100MB!');
        }
        return isLt100M;
    };
    handleChange = ({fileList}) => this.setState({fileList});

    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16}
        };
        const uploadProps = {
            name: 'files',
            action: 'https://www.easy-mock.com/mock/5bfbf83591ea222a361d8316/rich/file/upload',
            multiple: true,
            beforeUpload: this.beforeUpload,
            onChange: this.handleChange,
            fileList: this.state.fileList
        };
        const uploadButton = (
            <Button>
                <Icon type="upload"/> 選擇附件
            </Button>
        );
        return (
            <Row>
                <Col span={4}/>
                <Col span={16}>
                    <Form>
                        <Item label={'客戶單位'} {...formItemLayout}>
                            {getFieldDecorator('company', {
                                rules: [{
                                    required: true,
                                    message: '客戶單位不能爲空'
                                }]
                            })(
                                <Input/>
                            )}
                        </Item>
                        <Item label={'項目名稱'} {...formItemLayout}>
                            {getFieldDecorator('projectName', {
                                rules: [{
                                    required: true,
                                    message: '項目名稱不能爲空'
                                }]
                            })(
                                <Input/>
                            )}
                        </Item>
                        <Item label={'項目類型'} {...formItemLayout}>
                            {getFieldDecorator('projectCategory', {
                                rules: [{
                                    required: true,
                                    message: '項目類型不能爲空'
                                }]
                            })(
                                <Select labelInValue={true}>
                                    <Option key={'1'}>水庫大壩</Option>
                                    <Option key={'2'}>隧洞</Option>
                                    <Option key={'3'}>橋樑</Option>
                                    <Option key={'4'}>鐵路</Option>
                                    <Option key={'5'}>地鐵</Option>
                                    <Option key={'6'}>其他</Option>
                                </Select>
                            )}
                        </Item>
                        <Item label={'項目介紹'} {...formItemLayout}>
                            {getFieldDecorator('projectDesc', {
                                rules: [{
                                    required: true,
                                    message: '項目介紹不能爲空'
                                }]
                            })(
                                <Input.TextArea/>
                            )}
                        </Item>
                        <Item label={'聯繫人員'} {...formItemLayout}>
                            {getFieldDecorator('contact', {
                                rules: [{
                                    required: true,
                                    message: '聯繫人員不能爲空'
                                }]
                            })(
                                <Input/>
                            )}
                        </Item>
                        <Item label={'聯繫方式'} {...formItemLayout}>
                            {getFieldDecorator('phone', {
                                rules: [{
                                    required: true,
                                    message: '聯繫方式不能爲空'
                                }]
                            })(
                                <Input/>
                            )}
                        </Item>

                        <Item label={'軟件功能'} {...formItemLayout}
                              extra={'數據採集、儀器管理、數據管理、系統管理爲必選內容'}
                        >
                            {getFieldDecorator('softFunction', {
                                rules: [{
                                    required: true,
                                    message: '軟件功能不能爲空'
                                }]
                            })(
                                <Select
                                    mode={"multiple"}
                                    labelInValue
                                >
                                    <Option key={'1'}>數據採集</Option>
                                    <Option key={'2'}>儀器管理</Option>
                                    <Option key={'3'}>數據管理</Option>
                                    <Option key={'4'}>數據整編</Option>
                                    <Option key={'5'}>資料分析</Option>
                                    <Option key={'6'}>報表報告</Option>
                                    <Option key={'7'}>巡視檢測</Option>
                                    <Option key={'8'}>系統管理</Option>
                                </Select>
                            )}
                        </Item>
                        <Item
                            extra={'現場情況請輸入儀器類型、位置、供電情況、通信情況等'}
                            label={'現場情況'} {...formItemLayout}>
                            <div className={'rich-wrap'}>
                                {getFieldDecorator('scene', {
                                    validateTrigger: 'onBlur',
                                    initialValue: this.state.scene,
                                    rules: [{
                                        required: true,
                                        message: '現場情況不能爲空',
                                        validator: (_, value, callback) => {
                                            if (value.isEmpty()) {
                                                callback('請填寫現場情況')
                                            } else {
                                                callback()
                                            }
                                        }
                                    }]
                                })(
                                    <BraftEditor/>
                                )}
                            </div>
                        </Item>

                        <Item label={'項目建議'} {...formItemLayout}>
                            {getFieldDecorator('projectAdvice', {
                                rules: [{
                                    message: '項目建議不能爲空'
                                }]
                            })(
                                <Input.TextArea/>
                            )}
                        </Item>
                        <Item label={'上傳附件'}
                              extra={this.state.fileList.length > 0 ? null : '最多上傳一個附件,附件大小在100M以內'}
                              {...formItemLayout}>
                            {
                                getFieldDecorator('attachment', {})(
                                    <Upload {...uploadProps}>
                                        {this.state.fileList.length > 0 ? null : uploadButton}
                                    </Upload>
                                )
                            }
                        </Item>
                    </Form>
                </Col>
                <Col span={4}/>
            </Row>
        );
    }
}

AddForm = Form.create()(AddForm);

效果如下:

在這裏插入圖片描述

代碼

https://gitee.com/a2011102394/rich-text-editor.git

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