[英]Typescript React Functional Component with props.children
[英]React/TypeScript: Specifically type props.children to component
假設我們有一個渲染props.children
的組件Foo
和另一個組件Bar
。 兩個模塊都導出一個 props 接口。
有沒有辦法強制Foo
的孩子只能是Bar
類型?
理想情況下,我們可以在構建時使用 TypeScript 來完成此任務。
例子:
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>
);
};
注意:我們沒有使用 PropTypes
試試這個(參考)
export interface FooProps {
children?: React.ReactElement<BarProps> | React.ReactElement<BarProps>[]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.