我的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商店发送到我的反应组件,然后呈现标题以及草稿内容。
提前致谢。
答案 0 :(得分:2)
您应该通过道具将商店的一部分传递给编辑器组件。
<MyEditor article={storeSample.article} />
之后,您可以在此组件的constructor
方法中使用createWithContent
和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 readOnly
组件设置editorState
和Editor
属性:
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>