在Draft js中设置EditorState而不包含应用程序状态

时间:2018-10-04 12:13:00

标签: javascript reactjs draftjs

我想用一些初始内容更新JS草稿编辑器。我知道我们可以使用组件状态更改EditorState

import React from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState} from 'draft-js';

class MyEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {editorState: EditorState.createEmpty()};
    this.onChange = (editorState) => this.setState({editorState});
  }
  render() {
    return (
        <Editor editorState={this.state.editorState} onChange={this.onChange} />
    );
  }
}

每当我尝试在编辑器中更改某些内容时,它都会重新呈现。这导致一些性能问题。无论如何,我可以在不更改状态的情况下设置或更改编辑器的状态。与此类似

EditorState.set(editorState); //here editorState is new editor state;

任何想法如何实现?

1 个答案:

答案 0 :(得分:0)

经过两天的努力,我发现了一个有用的wysiwyg editor,它建立在Draft.js之上,具有很酷的功能。它具有Draft.js给定的所有功能。我们可以使用编辑器的refs加载现有内容。

import {EditorState, convertFromRaw} from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';


class myEditor extends Component {

   componentDidMount(){
       //I have stored rawContent in  database
       let rawContent={"blocks":[{"key":"3ge2q","text":"Hello World!;","type":"header-three","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}],"entityMap":{}};
       //Convert Raw to contentState
       let content=convertFromRaw(rawContent);
       let editorState=EditorState.createWithContent(content);
       this.refs.editor.editor.update(editorState); //Update the editor with updated content.
   }

    render(){
      <Editor
         ref="editor"
         wrapperClassName="demo-wrapper"
         editorClassName="template-editor"
         spellCheck={true}
         placeholder="Type something"
         onEditorStateChange={this.onEditorStateChange.bind(this)}
     />
  }
}