问题是:如何将draft-js内容保存为html,然后在页面上呈现内容(此时为html字符串)。
以为我会分享我学到的东西。
请在解决方案中找到一种使用draft.js保存和呈现内容的方法。
另外,请发布您自己的解决方案,以便我们都可以学习。
答案 0 :(得分:1)
经过无休止的搜索和搜索互联网如何使用draft.js建立我们正在建立的博客,我想我会分享我学到的东西。 Draft.js令人惊讶,但由于没有官方渲染解决方案,因此在保存后如何呈现数据并不是很清楚。
这是一个关于如何做到这一点的抽象演示。
插件用户为.Sheet {
margin-top: 100px;
margin-left: 25px;
margin-bottom: 30px; /* whatever value */
border-style: solid;
border-width: 2px;
padding: 20px;
background: red;
}
,draft-js
,draft-convert
。使用的数据库是react-render-html
创建帖子:
mongo
渲染帖子:
import React, {Component} from 'react';
import {
Block,
Editor,
createEditorState
} from 'medium-draft';
import { convertToHTML } from 'draft-convert';
class PostEditor extends Component {
constructor(props) {
super(props);
this.state = {
stateEditor: createEditorState()
}
this.onChange = (editorState) => {
this.setState({ editorState });
};
this.publishPost = this.publishPost.bind(this);
}
publishPost() {
// turn the state to html
const html = convertToHTML(this.state.editorState.getCurrentContent());
const post = {
content: html,
createdAt: new Date()
// more stuff...
}
// post the data to you mongo storage.
}
render() {
// get the editorState from the component State
const { editorState } = this.state;
return (
<div>
<Editor
ref="editor"
editorState={editorState}
placeholder="Write your blog post..."
onChange={this.onChange} />
<div>
<button onClick={this.publishPost} type="button">Submit</button>
</div>
</div>
)
}
}
注意:Html脚本标记已被转义。
虽然上述解决方案可能并不适用于所有用例,但我希望有人能发现它对基本用法有用。
免责声明:对于因使用上述代码而造成的任何损害或伤害,我概不负责。
答案 1 :(得分:1)
the documentation中有一个很好的例子来说明这个过程。这是link to the source code on Github。
基本上,您正在寻找的代码段是:
const sampleMarkup =
'<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
'<a href="http://www.facebook.com">Example link</a>';
const blocksFromHTML = convertFromHTML(sampleMarkup);
const state = ContentState.createFromBlockArray(blocksFromHTML);
this.state = {
editorState: EditorState.createWithContent(state),
};
效用函数称为convertFromHTML