我使用的数据库包含保存为简单 HTML 的文章,并且希望切换到与 React 配合良好的所见即所得,因此我正在研究 Lexical。
当用初始 HTML“喂养”Lexical 时,我需要首先将其转换为节点。但是:当初始 HTML 不是超级干净并且在 HTML 标记之间包含空格等时,转换就会中断。
所以这作为输入字符串可以工作:
const htmlString = '<p><b>I am bold</b></p><p><b><i>I am bold and italic</i></b></p>';
Run Code Online (Sandbox Code Playgroud)
但这并不:
const htmlString = '<p><b>I am bold</b></p> <p><b><i>I am bold and italic</i></b></p>';
Run Code Online (Sandbox Code Playgroud)
(因为 p 标签之间有空格)
我怎样才能解决这个问题?因为我无法确保源代码是格式良好的 HTML。
function InitialContentPlugin() {
const [editor] = useLexicalComposerContext();
editor.update(() => {
const htmlString = '<p><b>I am bold</b></p><p><b><i>I am bold and italic</i></b></p>';
const parser = new DOMParser();
const dom = parser.parseFromString(htmlString, 'text/html');
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom);
// Select the root
$getRoot().select();
// Insert them at a selection.
$insertNodes(nodes);
});
return null;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我发现空白区域创建了一个 TextNode。我无法将其插入到根中,因为 TextNode 是“叶子”,因此不允许作为根的直接子节点。现在需要找到一种方法来解决这个问题。
好的,我自己想出了一个简单的解决方案,删除根级别的“叶”节点:
editor.update(() => {
const htmlString = '<p><b>I am bold</b></p><br><p><b><i>I am bold and italic</i></b></p>';
const parser = new DOMParser();
const dom = parser.parseFromString(htmlString, 'text/html');
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom)
.map((node) => {
if (node.getType() === 'text') {
if (node.getTextContent().trim() === '') {
return null;
} else {
return $createParagraphNode().append(node);
}
}
if (node.getType() === 'linebreak') {
return null
}
return node;
})
.filter((node) => !!node);
// Select the root
$getRoot().select();
// Insert them at a selection.
$insertNodes(nodes);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
731 次 |
| 最近记录: |