如何在我的 react-component 中显示从后端接收到的 draft js 编辑器状态?

How to display the recieved editorstate of draftjs from backend in my react-component?

我的 redux 商店中有以下 json:

{
article:{
__v0:0,
_id:"5a573965d495833744d71f46",
draftcontent:"{\"entityMap\":{},\"blocks\":[{\"key\":\"6s7sp\",\"text\":\"IamBatman\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}]}",
title:"Batman",
type:"",
userId:"5a39538ee3d05642efdaf1dc"
},
}

其中 draftcontent 是用 draftjs 制作的内容。这是从后端获取的,现在我想将此 draftcontent 呈现为 draftjs 的 Editorstate,只读 属性 。所以基本上我需要一种方法将这些文章从我的 redux 商店获取到我的反应组件,然后呈现标题和草稿内容。

提前致谢。

您应该通过 props 将您的商店部分传递给您的编辑器组件。

<MyEditor article={storeSample.article} />

之后可以在该组件的constructor方法中使用createWithContent and convertFromRaw方法,启动draft-js组件,内容如下:

constructor(props) {
  super(props);

  const content = convertFromRaw(JSON.parse(props.article.draftcontent);
  const editorState = EditorState.createWithContent(content))

  this.state = {
    editorState: editorState
  };
}

render 方法中,您应该为 draft-js Editor 组件设置 readOnlyeditorState 属性:

render() {
  return (
    <div className="container-root">
      <h1>{this.props.article.title}</h1>
      <Editor
        readOnly={true}
        editorState={this.state.editorState}
        onChange={this._handleChange}
      />
    </div>
  );
}

在下面的隐藏代码段中检查工作演示(没有简化的 redux):

const {Editor, convertFromRaw, EditorState} = Draft;

const storeSample = {
  article:{
    __v0:0,
    _id:"5a573965d495833744d71f46",
    draftcontent:"{\"entityMap\":{},\"blocks\":[{\"key\":\"6s7sp\",\"text\":\"IamBatman\",\"type\":\"unstyled\",\"depth\":0,\"inlineStyleRanges\":[],\"entityRanges\":[],\"data\":{}}]}",
    title:"Batman",
    type:"",
    userId:"5a39538ee3d05642efdaf1dc"
  }
};

class MyEditor extends React.Component {
  constructor(props) {
    super(props);

    const editorState = EditorState.createWithContent(convertFromRaw(JSON.parse(props.article.draftcontent)))

    this.state = {
      editorState: editorState
    };
  }
  
  _handleChange = (editorState) => {
    this.setState({ editorState });
  }
  
  render() {
    return (
      <div className="container-root">
        <h1>{this.props.article.title}</h1>
        <Editor
          readOnly={true}
          editorState={this.state.editorState}
          onChange={this._handleChange}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <MyEditor article={storeSample.article} />,           document.getElementById('react-root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.7.0/Draft.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.10.0/Draft.js"></script>
<div id="react-root"></div>