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,所以会报错。

posted @ 2021-03-05 16:57  春燕啄春泥  阅读(2706)  评论(0编辑  收藏  举报