我正在尝试创建上下文 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'.
请指引我。
1条答案
按热度按时间ewm0tg9j1#
您需要使用
as
指令,例如useContext(NavContext) as NavContextType
。Typescript将知道该值不为空。