reactjs - 在 Typescript 中,如何确保 React 子组件属于特定类型

标签 reactjs typescript

我不知道如何在 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/

相关文章:

reactjs - react typescript : Object is possibly 'undefined'

angular - 用 angular2 *ngFor 填充表格?

javascript - 使用流实现去抖分块异步队列

javascript - 生产中的 Angular 应用程序路由错误

javascript - React如何检测路由变化方法

javascript - 如何将 refs 传递到 NavigationBar RouteMapper (React Native) 的变量中?

javascript - 为什么 ref 值增加两次

javascript - 样式未在组件中更新 - React

javascript - 为什么在推送更改检测时属性更改仍然导致 @Input 在 ngDoCheck 中发生更改?

angular - typescript observable .expand 用法