我可以在 TypeScript 中设置 child 的类型吗?
例如我有这样的组件
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 组件支持哪些特定的 child ,以避免这种情况:
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)。可以通过运行时自省(introspection)来完成(每个 child 的 type
属性)。
关于 typescript :如何在 react 组件中设置 child 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36085104/