react項目中Form表單中引用富文本編輯器react-quill


react項目中Form表單中引用富文本編輯器react-quill

安裝

npm i react-quill --save

安裝完之后頁面引入

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

初始化富文本實例,我寫在constructor 里,module也是寫在這里邊

constructor(props) { super(props); this.reactQuillRef = null; this.modules = null; }

因為我們圖片上傳沒有用base64,而是上傳到文件服務器上,返回一個圖片地址,所以我把modules寫在了componentDidMount函數內,基礎屬性如下:

componentDidMount(){
    const that = this; 
    this.modules = {
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
          ['blockquote', 'code-block'],
          [{'header': 1}, {'header': 2}],               // custom button values
          [{'list': 'ordered'}, {'list': 'bullet'}],
          [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
          ['image'], // a鏈接和圖片的顯示
          // [{'direction': 'rtl'}],                         // text direction
          // [{'color': []}, {'background': []}],   // dropdown with defaults from theme
          // [{'font': []}],
          // [{'align': []}],
          // [{ 'align': [] }],
        ],
        handlers: {
          image() {
            that.imageHandler();
          },
        },
      },
    }
  }

富文本組件react-quill參數

<FormItem {...formItemLayout} label="正文:">
	{getFieldDecorator("content", {
     // validateTrigger: "onBlur",   
      initialValue: "",
      rules: [{ required: true, message: "請輸入正文!" }]
  })(<ReactQuill 
     	theme="snow" 
     	style={{width: '100%'}}
  	modules={this.modules} 
        ref={(el) => { this.reactQuillRef = el }} />)}
</FormItem>

功能的開發—上傳本地圖片到服務器,代碼如下:

imageHandler = ()=> {
    const action =  api.FILE_ROOT;
    const input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');
    input.click();
    input.onchange = () => {
      const file = input.files[0];
      const fd = new FormData();
      fd.append('file', file);
      const hide = message.loading('上傳中...', 0);
      upload(action, fd).then(res => { // upload方法是封裝的上傳接口 action是上傳接口api地址
        if (res) {
          let quill = this.reactQuillRef.getEditor();//獲取到編輯器本身
          const cursorPosition = quill.getSelection().index;//獲取當前光標位置
          // res.url是上傳接口反回的服務器上的圖片地址鏈接
          quill.insertEmbed(cursorPosition, "image", res.url);//插入圖片 
          quill.setSelection(cursorPosition + 1);//光標位置加1
          hide();
          }
      });  
    };
  }

把react-quill富文本做進表單的時候,富文本沒有內容前提下,我只要改變了表單里的其他值,就會報如下錯誤:

You are passing the delta object from the onChange event back as value.

最后我在getFieldDecorator里面加了個initialValue:"",解決了

我覺得應該是沒有默認值時是個undefined,所以會報錯。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM