【问题标题】:What is the correct way to define a React component's contextTypes in TypeScript?在 TypeScript 中定义 React 组件的 contextTypes 的正确方法是什么?
【发布时间】: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。

【问题讨论】:

  • 如果你分享代码我可以看看。我个人还没有使用过contextrouter :)
  • 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


【解决方案1】:

在我们的职业生涯中,我们都曾多次遇到过这个问题。很奇怪我没听懂。

问题在于handleSubmit()this 的上下文因handleSubmit 的调用方式而异。将 handleSubmit 更改为粗箭头定义有效:

public handleSubmit = (event: React.FormEvent) => {

在这种特殊情况下,我忽略了这一点,因为我在 TypeScript 世界中并不经常遇到这个问题(我也不经常使用 DOM 元素,并且使用 React 不到一周... 没有借口,我知道)

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多