[英]React/TypeScript: Specifically type props.children to component
Let's say we have a component Foo
that renders props.children
and another component Bar
.假设我们有一个渲染
props.children
的组件Foo
和另一个组件Bar
。 Both modules export a props interface.两个模块都导出一个 props 接口。
Is there a way to enforce that Foo
's children can be only of type Bar
?有没有办法强制
Foo
的孩子只能是Bar
类型?
Ideally we could accomplish this with TypeScript at build-time.理想情况下,我们可以在构建时使用 TypeScript 来完成此任务。
Example:例子:
import { createElement, FC, ReactNode } from 'react';
import { Bar, BarProps } from '../Bar';
export interface FooProps {
children?: ReactNode; // this works
// children?: ReactNode<BarProps>; // nope
// children?: Bar; // nope
}
export const Foo: FC<FooProps> = (props) => {
return (
<div>
{props.children}
</div>
);
};
Note: we are not using PropTypes注意:我们没有使用 PropTypes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.