简体   繁体   English

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

[英]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

Try this ( reference )试试这个(参考

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM