刘少平 發表於 2019-11-14 16:26:00

react react-draft-wysiwyg使用

<div class="cnblogs_Highlighter">
<pre class="brush:html;gutter:true;">import * as Reactfrom '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
    width: 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&lt;IProps, IState&gt; {
    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: [],
            width: 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 =&gt; {
            this.setState({
                editorContent: html
            })
      }
      editor.create()
    }

    changePage = (currentPage) =&gt; {
      //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) =&gt; {
      // 修改月报审核状态
      confirm({
            title: '确定要删除该公告吗?',
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () =&gt; {
                // const param = {
                //   noticeId: id,
                  
                // }
                HttpClient.delete(`/api/notice/${id}`, {}).then((res: any) =&gt; {
               //   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) =&gt; {
      
      HttpClient.get(`/api/notice`, params).then((res: any) =&gt; {
         
            if (res.code === '0000') {
                if (res.data.records.length === 0) {
                  return
                }
                this.setState({
                  reportList: res.data.records,
                  firstDetailId: res.data.records.noticeId,
                  total: res.data.total
                }, () =&gt; {
                  const { firstDetailId, flagFirst } = this.state
                  if (flagFirst) {
                        this.setState({
                            Ind: 0
                        })
                        this.getDetailContent(firstDetailId)
                  }
                  
                  
                })
            }
         
      })
    }
    //
    // 获取详情内容
    getDetailContent = (id) =&gt; {
      // const param = {
      //   noticeId: id
      // }
      HttpClient.get(`/api/notice/${id}`, {}).then((res: any) =&gt; {
         
            if (res.code === '0000') {
                let data = res.data
                if (!data) return
                data.noticeFileList.map(file =&gt; {
                  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) =&gt; {
      this.setState({
            Ind: index,
            isShowNotice: true
      }, () =&gt; {
            this.getDetailContent(id)
      })
    }
    onShowSizeChange = (currentPage, pageSize) =&gt; {
      this.setState({
            currentPage,
            pageSize
      })
      const params = {
            pageNum: currentPage,
            pageSize,
          //picturecode
      }
      this.getMonthNoticeData(params)
    }
    toggleWidth = () =&gt; {
      const {width } = this.state
      if (width === 30) {
            this.setState({
                width: 360,
                collapsed: 'block'
            })
      } else {
            this.setState({
                width: 30,
                collapsed: 'none'
            })
      }
      
    }
   // 清空富文本的值
   clearContent = () =&gt; this.setState({ editorState: EditorState.createEmpty() })
    goAddMode = () =&gt; {
      this.setState({
            isShowNotice: false,
            flagFirst: false,
            uploadFileLists: []
      })
      this.props.form.getFieldsValue()
      this.clearContent()
      
    }
    beforeUpload = (file) =&gt; {
      console.log(file)
      this.setState(state =&gt; ({
            uploadFileLists: [...state.uploadFileLists, file],
      }))
      return false
    }
    onRemove = file =&gt; {
      this.setState((state) =&gt; {
            const index = state.uploadFileLists.indexOf(file)
            const newFileList = state.uploadFileLists.slice()
            newFileList.splice(index, 1)
            return {
                uploadFileLists: newFileList,
            }
      })
    }

    addNotice = () =&gt; {
      
      this.props.form.validateFields((err, values) =&gt; {
            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) =&gt; {
                  formData.append('uploadFile', item)
                  
                })
            }
         
            formData.append('title', values.title)
            formData.append('noticeContent',modalContent)
            HttpClient.post('/api/notice', formData).then((res: any) =&gt; {
                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) =&gt; {
      this.setState({
            editorState
      })
    }

   // 文件上传
uploadImageCallBack1 = (file) =&gt; {

return new Promise((resolve, reject) =&gt; {
      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) =&gt; {
    //         if (res.code === 'CODE_0000') {
    //               const imgurl = res.data.idFileName
    //               const imgObj = {
    //                   data: {
    //                     link:getImgPath () + imgurl
    //                   }
    //               }
    //               resolve(imgObj)
    //         }
    //       },
    //       error: () =&gt; {
    //         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 &amp;&amp; noticeFileList.length &gt; 0
      return (
            &lt;div className='MonthReport'&gt;
                &lt;img className='bgImg' src={bgImg} /&gt;
                &lt;Layout className='MonthReportCon'&gt;
                  &lt;Header className='MonthReportHead'&gt;
                        &lt;span&gt;系统公告&lt;/span&gt;
                        &lt;Button className='add-notice'   onClick={this.goAddMode}&gt;新增公告&lt;/Button&gt;
                  &lt;/Header&gt;
                  &lt;Layout className='MonthReportSec'&gt;
                        &lt;Sider width={width} className='MonthReportSider'&gt;
                            &lt;div className='toggleWidthBox'&gt;
                              {
                                    collapsed === 'block' ? &lt;Icon onClick={this.toggleWidth} className='toggleWidth' type='left-circle' /&gt;
                                    : &lt;Icon onClick={this.toggleWidth} className='toggleWidth' type='left-circle' /&gt;
                              }
                              
                            &lt;/div&gt;
                            &lt;div style={{display: collapsed, height: '100%'}}&gt;
                        &lt;div className='briefing-content-box'&gt;   
                        &lt;ul className='briefing-content-list'&gt;
                            {
                              reportList.map((item, index) =&gt; {
                                    return (
                                        &lt;li title={item.title} className={Ind === index ? 'active' : ''} onClick={() =&gt; this.getDetail(item.noticeId, index)}key={index}&gt;
                                          &lt;div className='left'&gt;
                                                {item.title}
                                          &lt;/div&gt;
                                          &lt;Icon onClick={() =&gt; this.onDelBulletin(item.noticeId)} title='删除' type='delete' className='delete-icon'/&gt;
                                        &lt;/li&gt;
                                    )
                                    
                              })
                            }

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

                                    &lt;div className='MonthReportContent-right'&gt;
                                                                        
                                          &lt;Form className='create-project-form' {...formItemLayout}&gt;
                                                &lt;Form.Item label='标题'&gt;
                                                    {getFieldDecorator('title', {
                                                      rules: [
                                                            { required: true, message: '请输入公告标题' },
                                                            { max: 100, message: '不能超过100个字符' }
                                                      ],
                                                    })(
                                                      &lt;Input allowClear placeholder='请输入公告标题' /&gt;
                                                    )}
                                                &lt;/Form.Item&gt;
                                                &lt;Form.Item className='ant-form-item-required' label='内容'&gt;
                                                    {getFieldDecorator('noticeContent', {
                                                      rules: [{ required: true, message: '请输入公告内容' }],
                                                    })(
                                                      &lt;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} },
                                                            }}
                                                      /&gt;
                                                      // &lt;TextArea autosize={{ minRows: 14, maxRows: 40 }} placeholder='请输入公告内容' /&gt;
                                                    )}
                                                      
                                                &lt;/Form.Item&gt;
                                                &lt;Form.Item label='附件'&gt;
                                                {getFieldDecorator('uploadFile', {
                                                    })(
                                                      &lt;Upload
                                                            name='file'
                                                            fileList={uploadFileLists}
                                                            beforeUpload={this.beforeUpload}
                                                            onRemove={this.onRemove}
                                                            accept='.pdf,.doc,.docx'
                                                      &gt;
                                                            &lt;Button&gt;
                                                                &lt;Icon type='upload' /&gt; 上传附件
                                                            &lt;/Button&gt;
                                                      &lt;/Upload&gt;
                                                    )}
                                                      
                                                &lt;/Form.Item&gt;
                                                &lt;Form.Item className='summit-btn'&gt;
                                                    &lt;Button type='primary' onClick={this.addNotice}&gt;发布&lt;/Button&gt;
                                                &lt;/Form.Item&gt;
                                          &lt;/Form&gt;
                                    &lt;/div&gt;
                            }
                           
                           &lt;/Content&gt;
                  &lt;/Layout&gt;
                  
                &lt;/Layout&gt;
            &lt;/div&gt;
      )
    }
}

export default Form.create&lt;IProps&gt;()(MonthReport)
</pre>
</div>
<p>  </p><br><br>
来源:https://www.cnblogs.com/whlBooK/p/11858191.html
頁: [1]
查看完整版本: react react-draft-wysiwyg使用