javascript - 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 属性。
解决方案
您不能在此处限制类型,因为渲染的 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!' }} />
推荐阅读
- ios - 在 didSelectRowAt indexPath 函数之外访问 IndexPath.row
- java - 在recyclerview中回收edittext
- swift - 如何实现一个符合相互关联协议之一的泛型类?
- jquery - 如何在jquery中取消选择选定的固定列数据表
- sql - SQL 查询中的 Microsoft.Azure.Documents.DocumentClientException
- python - 如何修复 rasberrypie3 python 中的“chrome 无法访问”和“DevToolsActivePort 文件不存在”错误
- node.js - 如何利用 Docker 在 Travis CI 上运行多种语言的测试
- getstream-io - 如何通过检查字段是否包含 GetStream-IO 上的字符串来查询频道
- angularjs - Angularjs Datatable 从列可见性中排除列
- r - 想知道在这种情况下我是否可以在这里使用 APPLY 而不是使用 FOR LOOP 进行优化?