首页 > 解决方案 > React Typescript - 反应组件类中的上下文

问题描述

我用 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始终为空。我this.state应用程序组件中放置了一个 div,它的值链接到它,它确实显示了与上下文不同的值。当代码以原始反应/创建反应应用程序编写时,我正在努力工作,而我在相同的组件下@types/react

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

标签: reactjstypescript

解决方案


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

所以React.createContext<{ name: string }>而不是React.createContext<typeof { name: string }>

这对我有用:

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>;
  }
}

推荐阅读