1

TLDR: Error message for SlateJS serializing to HTML Property 'children' does not exist on type 'Node[]'.

Going off on SlateJS Serializing Docs but in 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
  };
};

I'm getting the following property error for children, type and 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[]'

In my rich editor I have:

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>
  )

I already have the type dependencies.

  • "@types/slate-react": "^0.22.9"
  • "@types/slate": "^0.47.7",
4

2 回答 2

0

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>
  )
};
于 2020-08-26T13:51:15.813 回答
0

看起来您正在尝试访问节点数组而不是节点上的属性。

还有几件事值得一提:

  1. 更高版本的 Slate (.5x) 是用 TypeScript 编写的,不需要显式安装类型。您列出的那些 @types/xxx 依赖项不是正确的类型。它们适用于 0.47 倍。
  2. 请务必Node从 Slate ( import { Node } from 'slate') 导入类型。如果您不这样做并且它不是您想要的类型,则会使用一种全局可用的Node类型(这似乎不是您的问题,但对于遇到类似错误的其他人来说值得一提)
于 2020-09-27T21:42:27.163 回答