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
  };
};

对于孩子类型 url ,我收到以下属性错误。

  • 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>
  )
};
,

您似乎正在尝试访问节点阵列而不是节点上的属性。

还有两点值得一提:

  1. Slate的更高版本(.5x)用TypeScript编写,不需要显式安装。您列出的那些@ types / xxx依赖项不是正确的类型。它们是.47x。
  2. 请确保从Slate(Node)导入import { Node } from 'slate'类型。如果您不使用,则将使用一种全局可用的Node类型,而不是您想要的类型(这似乎不是您的问题,但遇到任何类似错误的其他人都应该提及)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...