reactjs 为什么typescript无法识别上下文 Package 器提供的值?

amrnrhlw  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(121)

我正在尝试创建上下文 Package 。将状态变量作为提供程序值传递,并尝试使用ToolBar组件中的useContext访问这些值。

type NavContextType = {
    isDrawerOpen: boolean;
    setIsDrawerOpen: React.Dispatch<React.SetStateAction<boolean>>;
};

export const NavContext = createContext<NavContextType | null>(null);

const NavBar: :ReactFC<ReactNode | undefined> = ({ children }) => {
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);

    return (
        <NavContext.Provider value={{ isDrawerOpen, setIsDrawerOpen }}>
            <ToolBar />
        </NavContext.Provider>
    );
};

Toolbar.js:

import { NavContext } from "./NavBar";

const ToolBar = () => {
    const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);
    return (
        .......
        .......
    );
};

当我尝试使用const { isDrawerOpen, setIsDrawerOpen } = useContext(NavContext);访问上下文值时,我得到如下类型的脚本错误:

TS2339: Property 'setIsDrawerOpen' does not exist on type 'NavContextType | null'.
        Property 'isDrawerOpen' does not exist on type 'NavContextType | null'.

请指引我。

ewm0tg9j

ewm0tg9j1#

您需要使用as指令,例如useContext(NavContext) as NavContextType。Typescript将知道该值不为空。

相关问题