如何在TypeScript中定义contextTypes
?
我有一个组件(注意:详见这个问题,但这在此处并不相关)。
export class Repos extends React.Component<ReposProps, {}> {
context: {
router: History
}
static contextTypes = {
router: React.PropTypes.object
};
它具备一个功能。
public handleSubmit(event: React.FormEvent) {
在该函数的结尾处,它调用了上下文。
this.context.router.push(path);
}
该组件具有表单功能。
public render() {
return (
{/* ... */}
<form onSubmit={this.handleSubmit}>
);
}
}
然而,在this.context.router.push(path);
这行代码上,我收到了错误消息"Uncaught TypeError: Cannot read property 'router' of undefined"。当编译这段代码时,我在使用 Repos in a Router 的文件中收到了 TypeScript 错误:
ERROR in ./index.tsx
(14,34): error TS2322: Type 'typeof Repos' is not assignable to type 'string | ComponentClass<any> | StatelessComponent<
any>'.
Type 'typeof Repos' is not assignable to type 'StatelessComponent<any>'.
Types of property 'contextTypes' are incompatible.
Type '{ router: Requireable<any>; }' is not assignable to type 'ValidationMap<any>'.
将contextTypes更改为
static contextTypes: React.ValidationMap<any> = {
router: React.PropTypes.object
};
我修复了TypeScript错误,尽管我怀疑这是不必要的;我怀疑另一个问题是导致这两个问题的原因。
根据在TypeScript问题4785:如何在TypeScript 1.6中使用React contextTypes?的讨论中,上述代码是正确的。如果有帮助的话,我正在使用TypeScript 1.7.3、React 0.14.7和react-router 2.0.0。
context
或router
:) - basarat