如何使用draft-js-html

时间:2019-06-05 05:58:08

标签: reactjs draftjs react-draft-wysiwyg

我需要在不同的字段中使用大约6个文本编辑器,以便用户可以将文本修改为粗体,斜体,下划线,向其中添加图像。我需要将数据以纯HTML格式发送到db并接收数据以相同的格式。我使用react-draft-wysiwyg进行转换draft-js-html。请帮我

  import React, { Component } from 'react';
  import { Editor } from 'react-draft-wysiwyg';
  import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
  import draftToHtml from 'draftjs-to-html';
  import { EditorState, convertToRaw} from 'draft-js';

  class Aboutus extends Component {
   constructor(props) {
   super(props);
    this.state = {
      editorStateLabel1: EditorState.createEmpty(),
      editorStateLabel2: EditorState.createEmpty(),
      aboutus:'',
      inProgress: false,
      uploadedImages:[],
     };
     this.onEditorStateChange = this.onEditorStateChange.bind(this);
     this.uploadCallback = this.uploadCallback.bind(this);
    }

    uploadCallback(file){
    let uploadedImages = this.state.uploadedImages
     const imageObject = {
     file: file,
     localSrc: URL.createObjectURL(file),
     }
    uploadedImages.push(imageObject);
    this.setState(uploadedImages:uploadedImages)
    return new Promise(
    (resolve, reject) => {
    resolve({ data: { link: imageObject.localSrc } });
    }
   );
   } 

     onEditorStateChange(type, editorState) {
       var aboutus = {};
       aboutus[type] = 
       draftToHtml(convertToRaw(editorState.getCurrentContent()))
       this.setState({
         aboutus
        });
       }

  render() {
    return (
     <div>
        <h4>label-1</h4>
         <Editor
           toolbar={{ image: { uploadCallback: this.uploadCallback 
            }}}
          editorState={this.state.aboutus.editorStateLabel1}
          onEditorStateChange={this.onEditorStateChange.bind(this, 
           'editorStateLabel1')}
        />
      </Col>
    </Row>
    <Row>
      <Col md={18}>
      <h4>label-2</h4>
        <Editor
          toolbar={{ image: { uploadCallback: this.uploadCallback 
            }}}
          editorState={this.state.aboutus.editorStateLabel2}
          onEditorStateChange={this.onEditorStateChange.bind(this, 
           'editorStateLabel2')}
        />
         </Col>
        </Row>
      </div>
      );
    }
  }
 export default Aboutus;

我遇到类似未捕获类型错误的错误:editorState.getImmutable不是函数

1 个答案:

答案 0 :(得分:0)

在第一次加载时,肯定会遇到问题,因为您的this.state.aboutus是字符串。您无法阅读''.editorStateLabel1。字符串在javascript中没有属性。

第二次加载时,您的this.state.aboutus.editorStateLabel1不是实际的editorState,而是HTML字符串。为了使DraftEditor正常工作,您需要使用EditorState API。仅在需要发送到DB的最后一分钟才转换为HTML。 Draft.js有其自己的数据结构-它不接受HTML也不分发HTML。在此处阅读文档:https://draftjs.org/docs/api-reference-content-state