【问题标题】:Using typescript with react, stateless component使用带有反应的无状态组件的打字稿
【发布时间】:2018-01-08 10:27:51
【问题描述】:
我想知道这些之间有什么区别,假设我没有使用状态:
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, {}> {}
或者它们的行为方式都一样吗?
【问题讨论】:
标签:
reactjs
typescript
components
state
【解决方案1】:
对于无状态组件有一个特殊的类型:
interface StatelessProps {}
const stateless: React.SFC<StatelessProps> = (props) => {
return <div />
}
【解决方案2】:
我们看看the type definitions就知道了:
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
class Component<P, S> {
/* ... */
}
P(props 的类型参数)和S(状态的类型参数)都默认为{},这意味着 props 和 state 的类型都是空对象。
所以在你指定的情况下:
- 您没有为
S 提供类型,因此默认为{}。
- 您提供
any 作为S 的类型 - 这不与{} 相同,因为它允许您将状态设置为任何东西(数字、字符串等)。鉴于setState API 的工作方式,我不知道这在实践中是否真的有效,但如果你愿意,可以尝试一下。
- 您提供
{} 作为S 的类型,与默认值相同。
所以简而言之,1 和 3 是一样的,但 2 不是。