我使用的是react-draft-wysiwyg编辑器,它建立在Draft.js之上。我试图找出,如何以编程方式插入HTML,如:
<h1>Hey</h1>
到目前为止,我得到的最接近的是使用Modifier模块的insertText()方法。例如:
insert = ()=>{
const editorState = this.state.editorState;
const selection = editorState.getSelection();
const contentState = editorState.getCurrentContent();
const ncs = Modifier.insertText(contentState, selection, "<h1>Hey</h1>",);
const es = EditorState.push(editorState, ncs, 'insert-fragment');
this.setState({editorState: es})
}
这会导致插入文字字符串,不是HTML H1元素。
怎么做?
答案 0 :(得分:1)
我找到了解决问题的方法:
您确实可以使用“ html-to-draftjs” 库。只需使用“ instert-fragment”并获取临时ContentState的BlockMap,如下所示:
import htmlToDraft from 'html-to-draftjs';
import { ContentState, EditorState, Modifier } from 'draft-js';
const data = "<h3>Dear member!</h3><p>This is a <b>TEST</b></p>"
let { contentBlocks, entityMap } = htmlToDraft(data);
let contentState = Modifier.replaceWithFragment(
editorState.getCurrentContent(),
editorState.getSelection(),
ContentState.createFromBlockArray(contentBlocks, entityMap).getBlockMap()
)
EditorState.push(editorState, contentState, 'insert-fragment')