2017-01-13 3 views
1

Вопрос: Как сохранить содержимое draft-js как html, а затем визуализировать содержимое (которое является строкой html в этой точке) на странице.Черновик js сохранение и отображение или отображение содержимого

Думал, что поделился бы тем, что узнал.

В решении можно найти один подход к сохранению и отображению содержимого с помощью draft.js.

Также, пожалуйста, разместите свои собственные решения, чтобы мы могли все учиться.

ответ

1

После бесконечного поиска и очистки Интернета, как использовать 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 были убежали.

Хотя решение выше может быть не идеальным для каждого случая использования, я надеюсь, что кто-то может найти его полезным для основного использования.

Отказ от ответственности: Я не несу ответственности за любой ущерб или вред, причиненный в результате использования вышеуказанного кода.

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

Смежные вопросы