首页 > 解决方案 > 在 Draft js 中设置没有应用程序状态的 EditorState

问题描述

我想用一些初始内容更新 Draft js Editor。我知道我们可以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;

知道如何实现吗?

标签: javascriptreactjsdraftjs

解决方案


经过两天的奋斗,我发现了一个有用的所见即所得编辑器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)}
     />
  }
}

推荐阅读