我不知道如何在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>[]
以及其他一些事情。
我发现了这个问题,但是我不太明白: Typescript: how to set type of children in React Component?
我确定我在做某事。任何建议表示赞赏。谢谢!
答案 0 :(得分:1)
您不能对子代的类型施加约束,但是可以对子代进行选择性渲染(或在运行时抛出异常)。
看看这段代码:
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
与您期望的不同,您当然可以抛出错误。
PS。这很冗长,可以优化为较小的方法,但这更容易理解。