React/TypeScript:专门输入 props.children 到组件

IT技术 reactjs typescript
2021-04-29 04:41:50

假设我们有一个Foo渲染props.children组件和另一个组件Bar两个module都导出一个 props 接口。

有没有办法强制 thatFoo的孩子只能是类型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

1个回答

试试这个(参考

export interface FooProps {
  children?: React.ReactElement<BarProps> | React.ReactElement<BarProps>[]
}