姜某 發表於 2019-11-14 16:24:00

react wangeditor使用

<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 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 confirm = Modal.confirm
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
    noticeFileList: any
    firstDetailId: any
    flagFirst: any
    isCurrent: any
    editorContent: any
    required: any
}

class MonthReport extends React.Component&lt;IProps, IState&gt; {
    iframe: any
    editorElem: any
    constructor(props: IProps) {
      super(props)
      
      const index = Number(wordIp.getQueryString(window.location.hash, 'index'))
      const id = wordIp.getQueryString(window.location.hash, 'id')
      this.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,
            required: true
      }
      this.editorElem = React.createRef()
      
    }
    componentWillMount() {
      const id = wordIp.getQueryString(window.location.hash, 'id')
      if (id) {
         //   console.log(id, index)
            this.getDetailContent(id)
      }
      
    }

    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,
         
      }
      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'
            })
      }
      
    }
    goAddMode = () =&gt; {
      this.setState({
            isShowNotice: false,
            flagFirst: false,
            required: true,
            uploadFileLists: []
      }, () =&gt; {
            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()
      })
      
      this.props.form.getFieldsValue()
    }
    beforeUpload = (file) =&gt; {
      
      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; {
      const {editorContent } = this.state
      if (editorContent) {
            this.setState({
                required: false
            }, () =&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',this.state.editorContent)
                  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('新增失败')
                        }
                     
      
                  })
                })
            })
      }
      
      
    }


    render() {
      
      const { pageSize, currentPage, total, reportList,width, collapsed,
            Ind, noticeContent, isShowNotice, uploadFileLists,noticeFileList, required } = 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: required, message: '请输入公告内容' }],
                                                    })(
                                                      &lt;div className='App'&gt;
                                                      
                                                            &lt;div ref={editorElem =&gt; this.editorElem = editorElem} style={{ textAlign: 'left' }} &gt; // Html代码
                                                            &lt;/div&gt;
                                                      &lt;/div&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/11858182.html
頁: [1]
查看完整版本: react wangeditor使用