我不知道如何在 Typescript 中完成这项工作。我有一个自定义 React 组件,它应该只接受某种类型的 React 组件作为子组件。我以为我可以做这样的事情,但它不起作用:
interface ChildProps {
firstName?: string;
lastName?: string;
}
interface ParentProps {
children: Child[]
}
const Child = ({firstName, lastName}: ChildProps) => {return <div>child</div>}
const Parent = ({children}:ParentProps) => {
return <div>{children}<div>
}
<Parent>
<Child> {/* should work */}
<Child> {/* should work */}
<Child> {/* should work */}
<div>this should throw error. Right?</div>
</Parent>
我希望的是我只能强制执行 Child
组件交给父级,我认为这很容易做到,但我有点难过。我试过了 children: Child[]
, 和 children: JSX.Element<Child>[]
, 以及其他一些东西。
我发现了这个 SO 问题,但我不太理解它: Typescript: how to set type of children in React Component?
我敢肯定这是我在做的蠢事。任何建议表示赞赏。谢谢!!
最佳答案
您不能对 child 的类型进行约束,但您可以对 child 进行选择性渲染(或在运行时抛出异常)。
看看这段代码:
private getCorrectChildren(): JSX.Element[] {
const result: JSX.Element[] = [];
React.Children.forEach(this.props.children, child => {
if (React.isValidElement(child)) {
if (child.type === MyTypeOfChildHere) {
result.push(child);
}
}
});
return result;
}
此方法可以在 render()
方法中调用,并且只会返回正确类型的子项。当然,如果 child.type
与您期望的不同,您可以抛出错误。
附言。这非常冗长,可以优化为更小的方法,但这更容易理解。
关于reactjs - 在 Typescript 中,如何确保 React 子组件属于特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56570843/