是否可以使用 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>;
}
我知道那个
ReactElement
在 preact-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/