【问题标题】:tiptap - Insert node below / at the end of the current onetiptap - 在当前节点下方 / 末尾插入节点
【发布时间】:2021-06-26 22:10:12
【问题描述】:

我正在尝试使用 reactjs 创建带有 tiptap 的文本编辑器。我想在编辑器的每个“块”旁边创建一个按钮(paragraph 块,blockquote 块,codeblock 块,...),允许用户在选定之前添加一个新的空块堵塞。它看起来像这样(概念编辑器):

所以我尝试这样做的方法是将光标位置设置在当前节点的末尾:

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 上制作了一个沙箱。要重现错误,您只需要专注于编辑器,随机写一些东西,然后单击+ 按钮。您应该会看到错误。

提前感谢您的帮助!

【问题讨论】:

  • props.getPosprops.node 定义在哪里?
  • 我编辑了我的帖子,但您可以在沙箱中看到完整的代码

标签: javascript reactjs tiptap prose-mirror


【解决方案1】:

当前解决方案


目前我发现的最佳解决方案:

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()

【讨论】:

    猜你喜欢
    • 2015-12-14
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 2020-11-15
    • 2021-05-23
    • 2015-02-08
    相关资源
    最近更新 更多