react react-draft-wysiwyg使用

import * as React  from 'react'
import { Layout, Pagination, Icon, Modal, message, Button, Form, Input, Upload } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { Editor } from 'react-draft-wysiwyg'
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css'
import {  ContentState, EditorState, convertToRaw } from 'draft-js'
import htmlToDraft from 'html-to-draftjs'
import draftToHtml from 'draftjs-to-html'
import E from 'wangeditor'
import iframeIp from '@config/index'
import './index.less'
import bgImg from '../../assets/images/index/home_bg.png'
import HttpClient from '@utils/HttpClient'
import wordIp from '@utils/wordDowload'



const { Header, Sider, Content } = Layout
// const { TextArea } = Input
const confirm = Modal.confirm
// const FormItem = Form.Item
export interface IProps extends FormComponentProps {
    form: any
   
}


interface IState {
    currentPage: any
    pageSize: any
    total:  any
    reportList: any
     any
    collapsed: any
    Ind: any
    noticeContent: any
    isShowNotice: any
    uploadFileLists: any
    editorState: any // 富文本编辑区
    noticeFileList: any
    firstDetailId: any
    flagFirst: any
    isCurrent: any
    editorContent: any
}

class MonthReport extends React.Component<IProps, IState> {
    iframe: any
    editorElem: any
    constructor(props: IProps) {
        super(props)
        const sampleMarkup = `` // 通知内容
        const blocksFromHTML = htmlToDraft(sampleMarkup)
        const state = ContentState.createFromBlockArray(
            blocksFromHTML.contentBlocks,
            blocksFromHTML.entityMap
        )
        const index = Number(wordIp.getQueryString(window.location.hash, 'index'))
        const id = wordIp.getQueryString(window.location.hash, 'id')
        this.state = {
            editorState: EditorState.createWithContent(state),
            editorContent: '好好学习天天向上',
            currentPage: 1,
            pageSize: 20,
            total: 0,
            reportList: [],
            noticeFileList: [],
             360,
            collapsed: 'block',
            Ind: index,
            noticeContent: '#',
            isShowNotice: true,
            uploadFileLists: [],
            firstDetailId: '0',
            flagFirst: false,
            isCurrent: id
        }
        this.editorElem = React.createRef()
      
    }
    componentWillMount() {
        const id = wordIp.getQueryString(window.location.hash, 'id')
        if (id) {
         //   console.log(id, index)
            this.getDetailContent(id)
        }
        const elem = this.editorElem
        const editor = new E(elem)
        // 使用 onchange 函数监听内容的变化,并实时更新到 state 中
        editor.customConfig.uploadImgMaxLength = 1
        // 限制图片大小
        editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024
        editor.customConfig.uploadImgShowBase64 = true
        editor.customConfig.onchange = html => {
            this.setState({
                editorContent: html
            })
        }
        editor.create()
    }
 
    changePage = (currentPage) => {
      //  console.log(currentPage)
        this.setState({
            currentPage
        })
        const { pageSize } = this.state
        const params = {
            pageNum: currentPage,
            pageSize,
          //  picturecode
        }
        this.getMonthNoticeData(params)
    }
    componentDidMount() {
        const params = {
            pageNum: 1,
            pageSize: 20
        }
        this.getMonthNoticeData(params)
    }
   
    onDelBulletin = (id) => {
        // 修改月报审核状态
        confirm({
            title: '确定要删除该公告吗?',
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                // const param = {
                //     noticeId: id,
                   
                // }
                HttpClient.delete(`/api/notice/${id}`, {}).then((res: any) => {
                 //   console.log(res)
                    if (res) {
                        message.success('删除成功')
                        const { currentPage, pageSize, isCurrent } = this.state
                        const params = {
                            pageNum: currentPage,
                            pageSize,
                        }
                        this.getMonthNoticeData(params)
                        if (isCurrent === id) {
                            this.setState({
                                flagFirst: true
                            })
                        }

                    } else {
                        message.success('删除失败')
                    }
                   
                })
            }
        })
    }
    getMonthNoticeData = (params) => {
       
        HttpClient.get(`/api/notice`, params).then((res: any) => {
         
            if (res.code === '0000') {
                if (res.data.records.length === 0) {
                    return 
                }
                this.setState({
                    reportList: res.data.records,
                    firstDetailId: res.data.records[0].noticeId,
                    total: res.data.total
                }, () => {
                    const { firstDetailId, flagFirst } = this.state
                    if (flagFirst) {
                        this.setState({
                            Ind: 0
                        })
                        this.getDetailContent(firstDetailId)
                    } 
                   
                   
                })
            }
           
        })
    }
    // 
    // 获取详情内容
    getDetailContent = (id) => {
        // const param = {
        //     noticeId: id
        // }
        HttpClient.get(`/api/notice/${id}`, {}).then((res: any) => {
         
            if (res.code === '0000') {
                let data = res.data
                if (!data) return 
                data.noticeFileList.map(file => {
                    file.uid = file.id
                    file.name = file.fileName
                    file.url =  `${iframeIp.iframeIp}/${file.filePath}`
                })
                this.setState({
                    // noticeContent: res.data.noticeContent,
                    noticeContent: `${iframeIp.iframeIp}/${res.data.noticeContent}`,
                    noticeFileList: data.noticeFileList,
                    flagFirst: false,
                    isCurrent: id
                })
            }
         
        })
    }
    // 点击侧边栏列表
    getDetail = (id, index) => {
        this.setState({
            Ind: index,
            isShowNotice: true
        }, () => {
            this.getDetailContent(id)
        })
    }
    onShowSizeChange = (currentPage, pageSize) => {
        this.setState({
            currentPage,
            pageSize
        })
        const params = {
            pageNum: currentPage,
            pageSize,
          //  picturecode
        }
        this.getMonthNoticeData(params)
    }
    toggleWidth = () => {
        const {width } = this.state
        if (width === 30) {
            this.setState({
                 360,
                collapsed: 'block'
            })
        } else {
            this.setState({
                 30,
                collapsed: 'none'
            })
        }
        
    }
     // 清空富文本的值
     clearContent = () => this.setState({ editorState: EditorState.createEmpty() })
    goAddMode = () => {
        this.setState({
            isShowNotice: false,
            flagFirst: false,
            uploadFileLists: []
        })
        this.props.form.getFieldsValue()
        this.clearContent()
      
    }
    beforeUpload = (file) => {
        console.log(file)
        this.setState(state => ({
            uploadFileLists: [...state.uploadFileLists, file],
        }))
        return false
    }
    onRemove = file => {
        this.setState((state) => {
            const index = state.uploadFileLists.indexOf(file)
            const newFileList = state.uploadFileLists.slice()
            newFileList.splice(index, 1)
            return {
                uploadFileLists: newFileList,
            }
        })
    }

    addNotice = () => {
      
        this.props.form.validateFields((err, values) => {
            if (err) {
                return
            }
        const modalContent = draftToHtml(convertToRaw((this.state.editorState.getCurrentContent())))
           const formData = new FormData()

            if (this.state.uploadFileLists.length) {
                this.state.uploadFileLists.map((item) => {
                    formData.append('uploadFile', item)
                  
                })
            }
          
            formData.append('title', values.title)
            formData.append('noticeContent',  modalContent)
            HttpClient.post('/api/notice', formData).then((res: any) => {
                if (res) {
                    message.success('新增成功')
                    this.setState({
                        isShowNotice: true,
                        flagFirst: true
                    })
                    const { currentPage, pageSize } = this.state
                    const params = {
                        pageNum: currentPage,
                        pageSize,
                    }
                    this.getMonthNoticeData(params)
                  
                } else {
                    message.success('新增失败')
                }
              

            })
        })
    }
 
      // 富文本值改变
      onEditorStateChange = (editorState) => {
        this.setState({
            editorState
        })
    }

     // 文件上传
  uploadImageCallBack1 = (file) => {
  
  return new Promise((resolve, reject) => {
      console.info(reject, resolve)
      const formData = new FormData()
      formData.append('uploadFile', file, file.name)
    //   reqwest({
    //       url: 'api/fileController/uploadFile', 
    //       method: 'post',
    //       headers: { 'Authorization': `Bearer${sessionStorage.getItem('token')}` },
    //       processData: false,
    //       data: formData,
    //       success: (res) => {
    //           if (res.code === 'CODE_0000') {
    //               const imgurl = res.data[0].idFileName
    //               const imgObj = {
    //                   data: {
    //                       link:  getImgPath () + imgurl
    //                   }
    //               }
    //               resolve(imgObj)
    //           }
    //       },
    //       error: () => {
    //           this.setState({
    //           })
    //           message.error('数据保存失败')
    //       },
    //   })

      }
    )

}

    render() {
       
        const { pageSize, currentPage, total, reportList,  width, collapsed,  
            Ind, noticeContent, isShowNotice, uploadFileLists, editorState, noticeFileList } = this.state
        const formItemLayout = {
            labelCol: { span: 1 },
            wrapperCol: { span: 23 },
        }
         const { getFieldDecorator } = this.props.form
         const hasFile = noticeFileList && noticeFileList.length > 0
        return (
            <div className='MonthReport'>
                <img className='bgImg' src={bgImg} />
                <Layout className='MonthReportCon'>
                    <Header className='MonthReportHead'>
                        <span>系统公告</span>
                        <Button className='add-notice'   onClick={this.goAddMode}>新增公告</Button>
                    </Header>
                    <Layout className='MonthReportSec'>
                        <Sider width={width} className='MonthReportSider'>
                            <div className='toggleWidthBox'>
                                {
                                    collapsed === 'block' ? <Icon onClick={this.toggleWidth} className='toggleWidth' type='left-circle' />
                                    : <Icon onClick={this.toggleWidth} className='toggleWidth' type='left-circle' />
                                }
                                
                            </div>
                            <div style={{display: collapsed, height: '100%'}}>
                        <div className='briefing-content-box'>    
                        <ul className='briefing-content-list'>
                            {
                                reportList.map((item, index) => {
                                    return (
                                        <li title={item.title} className={Ind === index ? 'active' : ''} onClick={() => this.getDetail(item.noticeId, index)}  key={index}>
                                            <div className='left'>
                                                {item.title}
                                            </div>
                                            <Icon onClick={() => this.onDelBulletin(item.noticeId)} title='删除' type='delete' className='delete-icon'  />
                                        </li>
                                    )
                                    
                                })
                            }

                                </ul>
                                <div className='toggle-page'>
                                    <Pagination 
                                        size='small' 
                                        pageSize={pageSize} 
                                        current={currentPage}
                                        total={total} 
                                        showTotal={num => `共 ${num} 条数据`}  
                                        onChange={this.changePage} 
                                        showSizeChanger
                                        onShowSizeChange={this.onShowSizeChange}
                                    />
                                </div>
                                </div>
                                </div>
                        </Sider>
                        <Content className='MonthReportContent'>
                            {
                                isShowNotice ?  
                                    <div className='MonthReportContent-right'>
                                    
                                            <h4>公告内容</h4>
                                        <div className='detail-con'>
                                           
                                            <iframe id='notice' src={noticeContent}></iframe>
                                              
                                        </div>
                                        {
                                            hasFile && 
                                            <div className='file-down'>
                                                <p className='title-label'>附件下载</p>
                                                <Upload fileList={noticeFileList} showUploadList={{showRemoveIcon: false}} />
                                            </div>
                                        }
                                       
                                    </div> : 

                                    <div className='MonthReportContent-right'>
                                                                        
                                            <Form className='create-project-form' {...formItemLayout}>
                                                <Form.Item label='标题'>
                                                    {getFieldDecorator('title', {
                                                        rules: [
                                                            { required: true, message: '请输入公告标题' },
                                                            { max: 100, message: '不能超过100个字符' }
                                                        ],
                                                    })(
                                                        <Input allowClear placeholder='请输入公告标题' />
                                                    )}
                                                </Form.Item>
                                                <Form.Item className='ant-form-item-required' label='内容'>
                                                    {getFieldDecorator('noticeContent', {
                                                        rules: [{ required: true, message: '请输入公告内容' }],
                                                    })(
                                                        <Editor   
                                                            wrapperClassName='demo-wrapper'
                                                            editorClassName='demo-editor'
                                                            editorState={editorState}
                                                            onEditorStateChange={this.onEditorStateChange}
                                                            placeholder='请输入公告内容'
                                                            name =  'nr'
                                                            localization={{locale: 'zh'}}
                                                            toolbar={{
                                                            options: ['inline', 'blockType', 'fontSize', 'fontFamily', 'list', 'textAlign', 'colorPicker', 'link', 'embedded',  'image', 'remove', 'history'],
                                                            image: {urlEnabled: true,
                                                                uploadEnabled: true,
                                                                alignmentEnabled: true,   // 是否显示排列按钮 相当于text-align
                                                                uploadCallback: this.uploadImageCallBack1,  previewImage: true,
                                                                inputAccept: 'image/*',
                                                                alt: {present: false, mandatory: false} },
                                                            }}
                                                        />
                                                        // <TextArea autosize={{ minRows: 14, maxRows: 40 }} placeholder='请输入公告内容' />
                                                    )}
                                                        
                                                </Form.Item>
                                                <Form.Item label='附件'>
                                                {getFieldDecorator('uploadFile', {
                                                    })(
                                                        <Upload 
                                                            name='file'
                                                            fileList={uploadFileLists}
                                                            beforeUpload={this.beforeUpload}
                                                            onRemove={this.onRemove}
                                                            accept='.pdf,.doc,.docx'
                                                        >
                                                            <Button>
                                                                <Icon type='upload' /> 上传附件
                                                            </Button>
                                                        </Upload>
                                                    )}
                                                        
                                                </Form.Item>
                                                <Form.Item className='summit-btn'>
                                                    <Button type='primary' onClick={this.addNotice}>发布</Button>
                                                </Form.Item>
                                            </Form>
                                    </div>
                            }
                           
                           </Content>
                    </Layout>
                  
                </Layout>
            </div>
        )
    }
}

export default Form.create<IProps>()(MonthReport) 

  

原文地址:https://www.cnblogs.com/whlBooK/p/11858191.html