我正在尝试使用 tiptap 创建一个文本编辑器使用 reactjs。我想在编辑器的每个“ block ”旁边创建一个按钮(paragraph
block ,blockquote
block ,codeblock
block ,...),允许用户在选定之前添加一个新的空 block 堵塞。它看起来像这样(概念编辑器):
所以我尝试这样做的方法是将光标的位置设置在当前节点的末尾:
src/components/blocks/Paragraph.js
const Paragraph = (props) => {
// ...
return {
// ...
<button onMouseDown={() => {
// ...
// props.getPos() gives the position at the beginning of the block
// props.node.nodeSize gives the "length" of the node
const endPos = props.getPos() + props.node.nodeSize;
props.editor.commands.focus(endPos);
// ...
}}>
Add block below
</button>
}
}
所以在这一点上,它起作用了。但是,当我尝试插入一个新的 node
在这个位置...// It will insert a paragraph node containing text "New block added"
props.editor.commands.insertContent({
"type":"paragraph",
"content":[
{
"type":"text",
"text":"New block added"
}
]
})
...我收到一个错误:TypeError: Cannot read property 'nodeType' of null
因此,为了让您详细了解此错误,我在 codesandbox.io 上制作了一个沙箱。要重现错误,您只需将注意力集中在编辑器上,随意写一些东西,然后单击 +
按钮。您应该看到错误。在此先感谢您的帮助 !
最佳答案
当前解决方案
目前我找到的最佳解决方案:
const endPos = props.getPos() + props.node.nodeSize
// I focus the start of the editor because
// when the cursor is at the end of the node below which
// we want to add a block, it doesn't focus the next block
props.editor.commands.focus('start')
props.editor
.chain()
.insertContentAt(endPos, {type: "paragraph"})
.focus(endPos)
.run()
关于javascript - tiptap - 在当前节点下方/末尾插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68146588/