【问题标题】:How to type check component children with Preact and TypeScript?如何使用 Preact 和 TypeScript 对子组件进行类型检查?
【发布时间】:2019-01-19 06:35:41
【问题描述】:

是否可以使用 TypeScript (v3.0.1) 和 Preact (v8.3.1) 对子组件进行类型检查?在 React 中有一个 ReactElement<T> 。 Preact 中有类似的东西吗?

我有一个menu 组件,它只能有menuItem 子组件。如何使用 TypeScript 在 Preact 中强制执行?使用 React,我可以执行以下操作:

interface Props {
    children?: React.ReactElement<MenuItem>[] | React.ReactElement<MenuItem>;
}

我知道ReactElement是在preact-compat中实现的,但我不想使用它。

感谢您的任何建议!

【问题讨论】:

    标签: reactjs typescript preact


    【解决方案1】:

    现在最简单的选项可能是 ComponentChildren 类型(请参阅此提交:https://github.com/preactjs/preact/commit/cd422d047f6d21607ff980c84b9c4ac1845ca798)。例如:

    import { h } from "preact";
    
    import type { ComponentChildren } from "preact";
    
    type Props = {
      children: ComponentChildren;
    }
    
    export function ComponentWithChildren(props: Props) {
      return (
        <div>
          {props.children}
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      Preact 的 ReactElement 等价物称为 VNode(虚拟 DOM 节点)。我绝不是 TypeScript 专家,但我相信您的示例可以如下工作:

      interface Props {
          children?: VNode<MenuItem>[] | VNode<MenuItem>;
      }
      

      在 Preact 8.3.0 之前,我认为我们依赖 JSX.Element 而不是 VNode

      【讨论】:

      • 感谢您的回答!好吧,它编译,但它也编译,当孩子不是 MenuItem&lt;div&gt; 时。
      • 您使用的是 Preact 8.3.0+ 吗?
      • 是的,我在"preact": "^8.3.1",
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-15
      • 2022-01-06
      • 2018-05-19
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2019-12-26
      相关资源
      最近更新 更多