如何在我的react-component中显示从后端收到的draftjs的editorstate?

时间:2018-01-13 09:46:22

标签: json reactjs react-redux draftjs

我的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制作的内容。这是从后端获取的,现在我想将此草稿内容呈现为具有只读属性的draftjs的Editorstate。所以基本上我需要一种方法将这些文章从我的redux商店发送到我的反应组件,然后呈现标题以及草稿内容。

提前致谢。

1 个答案:

答案 0 :(得分:2)

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

<MyEditor article={storeSample.article} />

之后,您可以在此组件的constructor方法中使用createWithContentconvertFromRaw方法,并以这种方式启动包含内容的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 readOnly组件设置editorStateEditor属性:

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>