我已经使用 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
始终为 null。我在 app 组件 中放置了一个 div,它的值链接到 this.state
,它确实显示了与上下文不同的值。当代码在原始 react /创建 react 应用程序中编写时,我正在努力工作,我在 @types/react
?
有谁知道如何在 typescript 中的组件类中实现上下文?
最佳答案
看起来像你的 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>;
}
}
关于reactjs - React Typescript - React 组件类中的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575461/