【发布时间】:2016-02-21 21:14:15
【问题描述】:
如何在 TypeScript 中定义contextTypes?
我有一个组件(注意:我不确定this question 中详述的必要类型的路由器,但这在这里应该无关紧要)
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); 行中,我收到错误“未捕获的 TypeError:无法读取未定义的属性‘路由器’”在编译相同的代码时,我在使用路由器中的 Repos 的文件中收到了 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 issue 4785: How to use React contextTypes in Typescript 1.6?的讨论,上面的代码是正确的。如果有帮助,我正在使用 TypeScript 1.7.3、React 0.14.7 和 react-router 2.0.0。
【问题讨论】:
-
如果你分享代码我可以看看。我个人还没有使用过
context或router:) -
Link to specific commit where things are broken -- 这可以使用 TypeScript 1.7.3 编译,但我只是注意到 1.8.2 破坏了它。使用 npm start 运行,导航到 localhost:8080/repos,输入两个文本字段并按 Go 以查看发生的路由器未定义错误。
-
我用临时修复 TS 1.8.2 编译问题更新了该 repo。
-
哇,我是个白痴。问题是绑定这个。我不知道是否适合保留这个问题或现在删除它。
标签: reactjs typescript