【问题标题】:DraftJS editor create from HTML is not working从 HTML 创建的 DraftJS 编辑器不起作用
【发布时间】:2018-11-13 17:50:13
【问题描述】:

编辑器正在启动,就好像它有空字符串一样!

我试过了:

EditorState.createWithContent(ContentState.createFromText('Hello'))

还有这个:

const html = '<p>Hey this <strong>editor</strong> rocks ????</p>';
const contentBlock = htmlToDraft(html);
if (contentBlock) {
  const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
  const editorState = EditorState.createWithContent(contentState);
  this.state = {
    editorState,
  };
}

还有这个:

import htmlToDraft from 'html-to-draftjs'
htmlToDraft(text)

没有任何效果!

【问题讨论】:

    标签: javascript reactjs editor draftjs


    【解决方案1】:

    你没有显示你对内容做了什么,但以下(即你的第一个选项)可以正常工作

    <Editor
       editorState={EditorState.createWithContent(
              ContentState.createFromText("Hello")
         )}
    />
    

    就像这样:

    import {
       Editor,
       EditorState,
       ContentState,
       convertFromHTML
    } from "draft-js";
    
    ...
    
    const blocksFromHTML = convertFromHTML(
      "<p>Hey this <strong>editor</strong> rocks ?</p>"
    );
    
    const content = ContentState.createFromBlockArray(
      blocksFromHTML.contentBlocks,
      blocksFromHTML.entityMap
    );
    
    return (
          <Editor editorState={EditorState.createWithContent(content)} />
    );
    

    【讨论】:

      【解决方案2】:

      如果您有兴趣,我已经通过功能组件将 HTML 引入 DraftJS 的编辑器。这是基于@Grantnz 的答案构建的代码。

      import React, { useState } from 'react'
      import { Editor, EditorState, RichUtils, ContentState, convertFromHTML } from 'draft-js'
      
      const DraftJS = () => {
          // assert hard-coded HTML string, convert it, bring it in as state
          const blocksFromHTML = convertFromHTML(
              "<p>Hey this <strong>editor</strong> rocks ?</p>"
          );
      
          const content = ContentState.createFromBlockArray(
              blocksFromHTML.contentBlocks,
              blocksFromHTML.entityMap
          );
      
          const [editorState, setEditorState] = useState(EditorState.createWithContent(content));
      
          // handle changes to the Editor component
          const onChange = editorState => {
            setEditorState(editorState);
          }
      
          // build the Editor component
          return (
            <div>
              <h4 className="green-text">From DraftJS.js</h4>
              <Editor
                editorState={editorState}
                onChange={onChange}
              />
            </div>
          );
      }
      
      export default DraftJS;
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多