Bru*_*uce 3 typescript reactjs
type ContextProps<T = object> = {
store: T,
updateStore: React.Dispatch<T>
};
export default React.createContext<Partial<ContextProps>>({}); // is there any way to pass the generic? so store can correct type
export function Provider<T, K>(props: T & { store: K }) {
const [globalState, updateStore] = React.useState(props.store);
const value = React.useMemo(
() => ({
store: globalState,
updateStore,
}),
[globalState],
);
return <StateMachineContext.Provider value={value} {...props} />;
}
Run Code Online (Sandbox Code Playgroud)
有什么方法可以将泛型传递到 Context 中,这样value就可以拥有正确的类型吗?
创建上下文时传递类型,记住在组件外部创建它。
type ContextProps<T = object> = {
store: T,
updateStore: React.Dispatch<T>
};
function createGenericContext<T extends object> () {
return React.createContext<Partial<ContextProps<T>>>({});
}
const StateMachineContext = createGenericContext<{type: 'a'}>();
// or just
const StateMachineContext = React.createContext<Partial<ContextProps<{type: 'a'}>>>({});
export function Provider<T, K>(props: T & { store: K }) {
const [globalState, updateStore] = React.useState(props.store);
const value = React.useMemo(
() => ({
store: globalState,
updateStore,
}),
[globalState],
);
return <StateMachineContext.Provider value={value} {...props} />;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2949 次 |
| 最近记录: |