javascript - 如何更改 SlateJS 节点元素 onChange 的属性?

标签 javascript reactjs slatejs

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

我有一个像以前一样的初始元素,注意到“id”属性了吗?在 OnChange 中,我想动态设置 id 属性。请参阅下面的实现,或多或少只是 SlateJs 的基本 react 设置

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

Slate React 组件

        <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…"
                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 Node 的 element 属性? Editor 类中是否有一些函数可以执行此操作?

最佳答案

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

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

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

关于javascript - 如何更改 SlateJS 节点元素 onChange 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71152875/

相关文章:

jquery - 如何使用 DJANGO REST 框架和 ajax 发出 POST 请求

javascript - 如何在 Cypress 中测试 Slate JS 行为

reactjs - 如何使用 React 测试库测试 `contenteditable` 事件

javascript - 从另一个测试调用另一个 Protractor 测试

javascript - 我们真的需要多线程 JavaScript 吗?

javascript - IE 中的 JQuery 错误,适用于 FF。可能live有问题

javascript - React hooks 无法通过动态命名正确更新状态

performance - 将react-addons-perf与react native结合使用

javascript - 如何为 Sequelize 更新添加日志记录