如何在 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/