如何将html转换为draftjs?

问题描述 投票:0回答:2

我已经尝试过基本的软件包,但我似乎不明白发生了什么,

这是我尝试过的;

const {
  convertFromHTML,
  ContentState
} = require('draft-js');
const htmlToDraft = require('html-to-draftjs');

const converter = () => {
    const sampleMarkup =
      '<b>Bold text</b>, <i>Italic text</i><br/ ><br />' +
      '<a href="http://www.google.com">Example link</a>';

    const blocksFromHTML = convertFromHTML(sampleMarkup);
    const state = ContentState.createFromBlockArray(blocksFromHTML);

    console.log('state: ', state);
}

converter();

使用哪个库非常清楚。 我得到的输出看起来很奇怪,我期望的看起来像这样;

{
  "blocks": [
    {
      "depth": 0,
      "inlineStyleRanges": [
        {
          "length": 9,
          "style": "BOLD",
          "offset": 0
        },
        {
          "length": 12,
          "style": "ITALIC",
          "offset": 11
        }
      ],
      "entityRanges": [
        {
          "length": 12,
          "key": 0,
          "offset": 25
        }
      ],
      "data": {},
      "text": "Bold text, Italics text\n\nexample link ",
      "key": "9jc4q",
      "type": "unstyled"
    }
  ],
  "entityMap": {
    "0": {
      "type": "LINK",
      "mutability": "MUTABLE",
      "data": {
        "url": "http://www.google.com",
        "targetOption": "_blank"
      }
    }
  }
}

有什么见解吗? (服务器端代码)

javascript reactjs draftjs
2个回答
3
投票
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.contentBlocks,
  blocksFromHTML.entityMap,
);

this.state = {
  editorState: EditorState.createWithContent(state),
};

2
投票

请使用此功能。 100% 工作

import htmlToDraft from 'html-to-draftjs';
import { ContentState, EditorState } from 'draft-js';


const htmlToDraftBlocks = (html) => {
 const blocksFromHtml = htmlToDraft(html);
 const { contentBlocks, entityMap } = blocksFromHtml;
 const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
 const editorState = EditorState.createWithContent(contentState);
 return editorState;
}


useEffect(()=>{
setEditorState(htmlToDraftBlocks("<p>Hello</p>"));
},[])
© www.soinside.com 2019 - 2024. All rights reserved.