reactjs - 如何使用 Preact 和 TypeScript 对组件子项进行类型检查?

标签 reactjs typescript preact

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

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

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

我知道那个ReactElementpreact-compat 中实现,但我不想使用它。

感谢您的任何建议!

最佳答案

现在最简单的选择可能是 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>
  );
}

关于reactjs - 如何使用 Preact 和 TypeScript 对组件子项进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51806928/

相关文章:

javascript - 如何不使用 Webpack 解析路径?

javascript - api返回的React js多个组件

typescript - Vscode API - provideTextDocument 执行不超过一次

typescript - Sequelize Typescript "id"列中的空值违反了非空约束

javascript - Angular Material Moment.js 格式化

reactjs - 在 Gatsby/React 中将文件作为字符串(或源 Assets )导入

javascript - 输入类型=从匿名函数调用时不触发文件单击

preact - 在 SSR 中同时渲染多个 preact-router 路由(在 Vercel 上)

javascript - 为什么 event.target.value 不包含数字输入的 "."和 "e"?

reactjs - React 组件上的 Jest 测试 : Unexpected token "<"