【问题标题】:React Typescript - Context in react component classReact Typescript - 反应组件类中的上下文
【发布时间】:2018-12-01 22:06:14
【问题描述】:

我使用 create react app 创建了一个 react typescript 应用程序。我现在想要一个我想要在我的所有组件中访问的上下文:

export const UserContext = React.createContext<{name: string}>({name: 'Foo'});

上下文与主应用组件的状态相关联。这种状态确实会改变,因此组件的上下文值也应该改变。

<UserContext.Provider value={this.state}>
    <MainPage/>
</UserContext.Provider>

我遵循了关于如何在组件的上下文中设置的文档字符串建议,所以有这个:

class MainPage extends React.Component {
   static contextType = UserContext;
   context!: React.ContextType<typeof UserContext>;

   public render() {
       return <div>{this.context.name}</div>
   }
}

但是this.context.name 始终为空。我在 应用程序组件 中放置了一个 div,它的值链接到 this.state,它确实显示了与上下文不同的值。当代码以原始反应/create-react-app 编写时,我正在努力工作,而我在@types/react 中相同的组件下?

有谁知道如何在 typescript 的组件类中实现上下文?

【问题讨论】:

  • @types/react 的行为并没有什么不同。它没有运行时行为,它只是一个声明文件,用于静态检查代码是否存在错误。

标签: reactjs typescript


【解决方案1】:

看起来你的UserContext 的类型参数有点错误。您需要删除typeof

所以React.createContext&lt;{ name: string }&gt; 而不是React.createContext&lt;typeof { name: string }&gt;

这对我有用:

import * as React from 'react';

const UserContext = React.createContext<{ name: string }>({ name: 'test' });

export class MainPage extends React.Component<undefined, undefined> {
  static contextType = UserContext;
  context!: React.ContextType<typeof UserContext>;

  public render() {
    return <div>{this.context.name}</div>;
  }
}

【讨论】:

  • 正确的是,界面前面不应该有typeof。我在写这个问题时犯了这个错误,因为我正在简化一个实际存在的更复杂的界面。所以删除了上下文的类型仍然不起作用???但是,如果我将您的代码复制到我的 reactapp 上方,则无法编译,因为它不喜欢没有默认关键字的类前面的导出,并且它也不喜欢 undefined 作为类型参数的类型参数。您使用的是哪个版本,因为我的版本可能不喜欢上下文?
  • 您遇到了什么错误?它们是打字稿错误,还是 lint 错误
  • 我只是在codesandbox上做的,只是检查了类型是否有效,但没有比这更进一步
猜你喜欢
  • 2019-10-06
  • 2019-06-10
  • 2019-11-21
  • 2020-01-21
  • 1970-01-01
  • 2019-11-18
  • 2021-01-06
  • 1970-01-01
  • 2019-09-22
相关资源
最近更新 更多