我已经使用 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
始终为空。我在 app 组件中放置了一个 div,其值链接到
this.state
,并且它确实显示了与上下文不同的值。我很挣扎,因为代码在原始 React / create-react-app 中编写时可以工作,并且我在 @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>;
}
}
取自React文档:
// For TS pre-3.7:
static contextType = UserContext
context!: React.ContextType<typeof UserContext>
// For TS 3.7 and above:
static contextType = UserContext
declare context: React.ContextType<typeof UserContext>