reactjs - 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
?
有谁知道如何在打字稿的组件类中实现上下文?
解决方案
看起来您的类型参数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>;
}
}
推荐阅读
- vue.js - 防止元素之间的Vue渲染换行符
- java - javax.persistence.PersistenceException:org.hibernate.SessionException:会话已关闭
- android-studio - 由于 gpu 驱动程序问题,无法在虚拟机上运行模拟器。是否可以在 vm 或嵌套 vm 中运行 avd?
- eclipse - 无法在 Eclipse Helios 中安装 SonarLint
- android - 脱机时运行颤振 - 停留在解决依赖关系上
- c - sprintf 堆栈缓冲区溢出
- corda - 无法将corda 3.3 升级到corda 4.0
- c++ - 赋值操作时调用析构函数
- php - 自定义页面 Opencart 的分页
- python - 为什么nodejs和python中符号''的unicode值不同?