加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – Typescript:如何在React Component中设置子类型?

发布时间:2020-12-15 20:49:00 所属栏目:百科 来源:网络整理
导读:我可以在TypeScript中设置子类型吗? 例如,我有这样的组件 class UserProfile extends React.Component{ id: number },void{}class Thumbnail extends React.Component{ children: UserProfile[] },void{}class UsersList extends React.Componentvoid,void{
我可以在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>
        )
    }
}

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

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>
        )
    }
}

这个例子不起作用,但是有什么方法可以做到吗?

set type of children in React Component?

不能用类型注释缩小(它的所有JSX.Element).可以使用运行时内省(每个子项的type属性)来完成.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读