首页 > 解决方案 > Typescript - 限制将有效道具传递给 React 组件

问题描述

是否可以限制将有效道具传递给反应组件?

例子:

<SomeComponent primaryCTA={<Button size="small">Click here</Button} />

现在,在上面的代码中,我希望用户不能提供size道具。

这就是 SomeComponent 的类型 Props 的样子

type SomeComponentProps = {
  primaryCTA: React.ReactElement<
     Exclude<ButtonProps, 'size'>,
     typeof Button>;
}

但是,上面的代码不起作用。您仍然可以为 SomeComponent 中的 Button 组件提供 size 属性。

标签: javascriptreactjstypescript

解决方案


您不能在此处限制类型,因为渲染的 JSX 不携带渲染它的组件的类型。这意味着没有类型信息可以限制:

const button = <Button size="small">foo</Button> // type: JSX.Element

相反,通常最好SomeComponent通过公开有关如何执行此操作的道具来处理创建按钮。

例如,如果primaryCTA输入为string,那么在您的SomeComponent渲染中您可以创建按钮:

function SomeComponent({ primaryCTA }: Props) {
  return <Button size="small-or-whatever">{primaryCTA}</Button>
}

或者,您可以制作所期望primaryCTA的道具类型。Button

您可以使用React.ComponentProps<typeof Button>Button组件中获取道具类型,然后您可以使用Omit<Props, 'size'>删除您不想公开的任何内容。最后,您可以将这些道具传播回按钮<Button {...primaryCTA} />

将它们放在一起,您可以执行以下操作:

interface SomeComponentProps {
    primaryCTA: Omit<React.ComponentProps<typeof Button>, 'size'>
}

function SomeComponent({ primaryCTA }: SomeComponentProps) {
    return <>
        <div>Testing this component</div>
        <Button {...primaryCTA} size='small' />
    </>
}

// Usage of SomeComponent
<SomeComponent primaryCTA={{ color: 'red', children: 'click here!' }} />

操场


推荐阅读