nach endlosen Suche und Reinigung des Internets für die Verwendung von draft.js für einen Blog, den wir bauen, dachte ich, ich würde teilen, was ich gelernt habe. Draft.js ist erstaunlich, aber es ist nicht sehr klar, wie man die Daten nach dem Speichern rendert, da es keine offizielle Render-Lösung gibt.
Hier ist eine abstrakte Demo, wie man das machen könnte.
Plugins Benutzer waren draft-js
, draft-convert
, react-render-html
. Datenbank verwendet wurde mongo
erstellen Beitrag:
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>
)
}
}
machen den Beitrag:
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>
)
}
}
Hinweis: HTML-Script-Tags entgangen sind.
Obwohl die obige Lösung möglicherweise nicht für jeden Anwendungsfall perfekt ist, hoffe ich, dass jemand sie für die grundlegende Verwendung nützlich finden kann.
Haftungsausschluss: Ich hafte nicht für Schäden oder Schäden, die durch die Verwendung des obigen Codes verursacht werden.