2017-01-13 1 views
1

질문은 다음과 같습니다. 초안 -js 콘텐트를 html로 저장하고 나중에이 콘텐트 (이 시점에서 html 문자열)를 페이지에 어떻게 렌더링합니까?초안 js 저장 및 렌더링 또는 내용 표시

생각 나는 내가 배운 것을 나누겠다.

draft.js를 사용하여 콘텐츠를 저장하고 렌더링하는 한 가지 방법을 찾아보십시오.

우리 모두가 배울 수 있도록 자신의 솔루션을 게시하십시오.

답변

1

우리가 만들고있는 블로그에 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 스크립트 태그를 탈출했다.

위의 솔루션이 모든 유스 케이스에 완벽하지는 않지만 누군가 기본 사용법에 유용하게 활용되기를 바랍니다.

면책 조항 : 위의 코드를 사용함으로써 발생하는 모든 손해 또는 손해에 대해 책임을지지 않습니다.

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