使用具有反应打字稿,无状态组件
问题描述:
我想知道它们之间的区别是,我不使用状态假设:使用具有反应打字稿,无状态组件
1. export class SkillList extends React.Component<SkillListProps> {}
2. export class SkillList extends React.Component<SkillListProps, any> {}
3. export class SkillList extends React.Component<SkillListProps, {}> {}
还是他们都以同样的方式表现?
答
让我们来看看the type definitions,并找出:
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
class Component<P, S> {
/* ... */
}
两个P
(对于道具的类型参数)和S
(为国家的类型参数)默认为{}
,这意味着,无论是道具和状态有一个空对象的类型。
所以在情况下,您所指定:
- 你不为
S
提供一个类型,所以它默认为{}
。 - 您提供
any
为S
类型 - 这是不一样{}
,因为它可以让你的状态设置为所有东西(一个数字,字符串,等等)。考虑到setState
API的工作方式,我不知道这是否会在实际中起作用,但如果您愿意,可以尝试。 - 您提供
{}
作为S
的类型,与默认相同。
所以总之,1和3是相同的,但2不是。
答
对无状态组件有一个特殊类型:
interface StatelessProps {}
const stateless: React.SFC<StatelessProps> = (props) => {
return <div />
}