首页 > 解决方案 > 从 HTML 创建的 DraftJS 编辑器不起作用

问题描述

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

我试过这个:

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)

没有任何效果!

标签: javascriptreactjseditordraftjs

解决方案


您没有显示您对内容所做的操作,但以下(即您的第一个选项)可以正常工作

<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)} />
);

推荐阅读