打字稿检查特定组件的反应子项

时间:2021-03-18 11:35:07

标签: reactjs typescript jsx

我有一个带孩子的组件:

interface FooProps {
  title: string;
}

const Foo: React.FC<FooProps> = ({ children, title }) => (
  <div>
    <h1>{title}</h1>
    {children}
  </div>
);

现在我想限制 children 只接受一个特定的组件 - 比如说一个 Button 组件。有没有办法在 FooProps 中定义它?

一种常见的方法似乎是:

interface FooProps {
  children: React.ReactElement<Button>;
  title: string;
}

然而,只要子道具正确,这只会检查是否传递了任何元素。我的 Button 组件可能没有任何必需的 props,因此这种技术最终将允许任何子类型。有没有更强大的输入方式?

0 个答案:

没有答案