如何解决SlateJS Typscript node.children的url和type属性不存在
TLDR:
SlateJS序列化为HTML的错误消息
Property 'children' does not exist on type 'Node[]'
。
以SlateJS Serializing Docs开头,但以tsx开头。
import React,{ useCallback,useMemo,useState } from "react";
import escapeHtml from 'escape-html';
import { Editor,createEditor,Node,Text } from 'slate';
import { withHistory } from 'slate-history';
const serializeHTML = (node: Node[]) => {
if (Text.isText(node)) {
return escapeHtml(node.text)
};
const children = node.children.map((n: Node[]) => serializeHTML(n)).join('');
switch (node.type) {
case 'link':
return `<a href="${escapeHtml(node.url)}">${children}</a>`
case 'list-item':
return ``
case 'paragraph':
return `<p>${children}</p>`
case 'quote':
return `<blockquote>${children}</blockquote>`
default:
return children
};
};
-
Property 'children' does not exist on type 'Node[]'
-
Property 'type' does not exist on type 'Node[]'
-
Property 'url' does not exist on type 'Node[]'
在我的丰富编辑器中,我有:
const RichTextEditor = (props: RichTextEditorProps) => {
const editor = useMemo(() => withImages(withHistory(withReact(createEditor()))),[]);
const [value,setValue] = useState<Node[]>(initialValue);
const html = serializeHTML(value);
return (
<Slate editor={editor} value={value} onChange={newValue => setValue(newValue)}>
...
</Slate>
)
我已经有了类型依赖项。
-
"@types/slate-react": "^0.22.9"
-
"@types/slate": "^0.47.7",
解决方法
serializeHTML()
方法可以只使用一个Node并从其调用位置获取迭代器。
功能:
const serializeHTML = (node: Node) => {
...
const children = node.children.map((n: Node) => serializeHTML(n)).join('');
...
};
致电:
const RichTextEditor = (props: RichTextEditorProps) => {
const editor = useMemo(() => withImages(withHistory(withReact(createEditor()))),[]);
const [value,setValue] = useState<Node[]>(initialValue);
const html = value.map(v => serializeHTML(v)).join('');
return (
<Slate editor={editor} value={value} onChange={newValue => setValue(newValue)}>
...
</Slate>
)
};
,
您似乎正在尝试访问节点阵列而不是节点上的属性。
还有两点值得一提:
- Slate的更高版本(.5x)用TypeScript编写,不需要显式安装。您列出的那些@ types / xxx依赖项不是正确的类型。它们是.47x。
- 请确保从Slate(
Node
)导入import { Node } from 'slate'
类型。如果您不使用,则将使用一种全局可用的Node
类型,而不是您想要的类型(这似乎不是您的问题,但遇到任何类似错误的其他人都应该提及)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。