typescript:如何在 React 组件中设置孩子的类型?

IT技术 reactjs typescript react-jsx
2021-04-27 15:30:02

我可以在 TypeScript 中设置孩子的类型吗?

例如我有这样的组件

class UserProfile extends React.Component<{ id: number }, void>{
}

class Thumbnail extends React.Component<{ children: UserProfile[] }, void>{

}

class UsersList extends React.Component<void, void>{

    public render() {
        return (
            <div>
                <Thumbnail><UserProfile id={1} /></Thumbnail>
                <Thumbnail><UserProfile id={2} /></Thumbnail>
            </div>
        )
    }
}

我想定义 Thumbnail 组件中支持哪些特定子项以避免这种情况:

class UsersList extends React.Component<void, void>{

    public render() {
        return (
            <div>
                <Thumbnail><UserProfile id={1} /></Thumbnail>
                <Thumbnail><UserProfile id={2} /></Thumbnail>
                <Thumbnail><span>Some plain text</span></Thumbnail> // This should be forbidden because Thumbnail component expects to have an array of UserProfile elements as it can handle them
            </div>
        )
    }
}

这个例子不起作用,但有什么办法吗?

1个回答

在 React 组件中设置孩子的类型?

不能用类型注解来缩小(都是 JSX.Element)。可以通过运行时内省(type每个孩子的属性)来完成。