После бесконечного поиска и очистки Интернета, как использовать draft.js для блога, который мы строим, я думал, что поделюсь тем, что узнал. Draft.js AMAZING, но не очень понятно, как отображать данные после сохранения, так как нет официального решения для рендеринга.
Вот абстрактная демонстрация о том, как это можно сделать.
Пользователями плагинов были 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 были убежали.
Хотя решение выше может быть не идеальным для каждого случая использования, я надеюсь, что кто-то может найти его полезным для основного использования.
Отказ от ответственности: Я не несу ответственности за любой ущерб или вред, причиненный в результате использования вышеуказанного кода.