React createContext issue in Typescript?

前端 未结 2 569
一个人的身影
一个人的身影 2021-02-02 08:33

So I\'m having a very weird issue with React Context + Typescript.

Working example

In the above example, you can see what I\'m trying to do actually work. Essen

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 09:15

    I had a fun time with this so I figured I'd share what I came up with.

    The SidebarProps represent the context's state. Everything else, besides the reducer actions, can essentially be used as is.

    Here is a nice article explaining the exact same workaround (Not in TypeScript) : Mixing Hooks and Context Api

    import React, { createContext, Dispatch, Reducer, useContext, useReducer } from 'react';
    
    interface Actions {
        type: string;
        value: any;
    }
    
    interface SidebarProps {
        show: boolean;
        content: JSX.Element | null;
    }
    
    interface SidebarProviderProps {
        reducer: Reducer;
        initState: SidebarProps;
    }
    
    interface InitContextProps {
        state: SidebarProps;
        dispatch: Dispatch;
    }
    
    export const SidebarContext = createContext({} as InitContextProps);
    export const SidebarProvider: React.FC = ({ reducer, initState, children }) => {
        const [state, dispatch] = useReducer(reducer, initState);
        const value = { state, dispatch };
        return (
            
                {children}
            
        );
    };
    export const useSidebar = () => useContext(SidebarContext);
    
    const SidebarController: React.FC = ({ children }) => {
        const initState: SidebarProps = {
            show: false,
            content: null
        };
    
        const reducer: Reducer = (state, action) => {
            switch (action.type) {
                case 'setShow':
                    return {
                        ...state,
                        show: action.value
                    };
    
                case 'setContent':
                    return {
                        ...state,
                        content: action.value
                    };
    
                default:
                    return state;
            }
        };
    
        return (
            
                {children}
            
        );
    };
    
    export default SidebarController;
    

提交回复
热议问题