1

如何在 SlateJS OnChange 方法中更改节点元素属性?

我有一个像以前一样的初始元素,注意“id”属性吗?在 OnChange 中,我想动态设置 id 属性。见下文实现,或多或少只是 SlateJs 的基本反应设置

const initialValue: Descendant[] = [
    {
        type: 'paragraph',
        id: '',
        children: [
            {
                text:
                    'This is editable plain text, just like a <textarea>!',
            },
        ],
    },
]

板岩反应组件

        <Slate
            editor={editor}
            value={textContent}
            onChange={currTextContent => {
                // Logic for newlines
                if (currTextContent.length > textContent.length) {
                    // Same example from slatejs on how to save content
                    const isAstChange = editor.operations.some(
                        op => 'set_selection' !== op.type,
                    )

                    if (isAstChange) {
                        // Set id property of new line
                        currTextContent[0].id = 'test'
                    }
                }

                settextContent(currTextContent)
            }}>
            <Editable
                placeholder="Enter some rich text…&quot;
                spellCheck
                autoFocus
            />
        </Slate>

但是,它说 .id 属性是只读的。如果我尝试设置整个对象,也会发生同样的情况。它是只读的。通过 currTextContent[0].newID 添加新属性也会出错,对象不可扩展

                    currTextContent[0] = {
                        type: 'paragraph',
                        id: '',
                        children: [
                            {
                                text:
                                    'This is editable plain text, just like a <textarea>!',
                            },
                        ],
                    }

如何在 onChange 方法中更改(或添加)SlateJS 节点的元素属性?在 Editor 类中是否有一些功能可以做到这一点?

4

1 回答 1

0

因此,您实际上无法更改 onChange 中的节点,因为它们是只读的。相反,您需要使用 Slate API 转换来插入或添加新的属性,如下所示。

    Transforms.setNodes(
        editor,
        {
            id: '123',
        },
        { at: [0] },
    )

这会将属性 id = 123 插入节点 [0]。

于 2022-02-19T00:41:16.923 回答