现在的问题是:我如何将draft-js内容保存为html,然后在页面上呈现该内容(此时是一个html字符串)。
我想分享一下我学到的东西。
请在解决方案中找到一种使用draft.js保存和呈现内容的方法。
此外,请发布您自己的解决方案,以便我们都可以学习。
发布于 2017-01-13 20:16:26
在无休止地搜索和搜索互联网上如何使用draft.js创建博客之后,我想我应该分享我学到的东西。Draft.js很神奇,但在保存后如何渲染数据还不是很清楚,因为没有官方的渲染解决方案。
这是一个关于如何做到这一点的抽象演示。
插件用户有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>
)
}
}渲染帖子:
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>
)
}
}注意: Html脚本标记已被转义。
虽然上面的解决方案可能不是对每个用例都完美,但我希望有人能发现它对基本用法有用。
免责声明:对于因使用上述代码而造成的任何损害或伤害,我不承担任何责任。
发布于 2017-01-21 19:06:58
在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
https://stackoverflow.com/questions/41634473
复制相似问题