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>
)
}
}
渲染帖子:
import React, { Component } from 'react';
import renderHTML from 'react-render-html';
class PostArticle extends Component {
constructor(props) {
super(props);
this.state = {
text: null
}
}
componentWillMount() {
// get the data from the database
const post = getMyBlogPostFunction(); // replace getMyBlogPostFunction with own logic to fetch data
this.setState({ text: post.content })
}
render() {
return (
<div className='article-container'>
{renderHTML(this.state.text)}
</div>
)
}
}
import draftToHtml from 'draftjs-to-html';
const rawContent = typeof storyBehind === 'string' ? JSON.parse(storyBehind) : storyBehind; //convert to raw object If storyBehind is a serialized JSON string instead of a raw object
const text=draftToHtml(rawContent)
3条答案
按热度按时间nnvyjq4y1#
在无休止地搜索和搜索互联网如何使用draft.js为我们正在建设的博客之后,我想我会分享我学到的东西。Draft.js非常棒,但是由于没有官方的渲染解决方案,因此在保存后如何渲染数据并不是很清楚。
这里有一个抽象的演示如何做到这一点。
插件用户为
draft-js
、draft-convert
、react-render-html
。使用的数据库为mongo
创建帖子:
渲染帖子:
注意:Html脚本标记已转义。
虽然上面的解决方案可能不适合每个用例,但我希望有人能发现它对基本用法有用。
免责声明:我不承担任何损害,或通过使用上述代码造成的伤害。
eqoofvh92#
文档中有一个很好的示例演示了这个过程。这是一个link to the source code on Github。
基本上,您正在寻找的代码片段是这样的:
该实用程序函数称为
convertFromHTML
nimxete23#
Draft.js内容通常存储为序列化的JSON对象,其中包括有关文本块、内联样式和实体的信息。要在网页中显示此内容,您需要将其转换回HTML或纯文本。
Draft.js并没有为这种转换提供现成的解决方案,但是有几个库可以提供帮助。一个流行的选择是draftjs-to-html。
在这里,storyBehind是一个草稿。JS内容存储在DB中。现在您可以将文本显示为,