1. 创建文件 viewportContext.tsx
import React from "react";
const defaultValue = { width: window.innerWidth } const viewportContext = React.createContext(defaultValue);const ViewportProvider = ({ children }) => { const [width, setWidth] = React.useState(window.innerWidth); const handleWindowResize = () => { setWidth(window.innerWidth); } React.useEffect(() => { window.addEventListener("resize", handleWindowResize); return () => window.removeEventListener("resize", handleWindowResize); }, []); return ( <viewportContext.Provider value={{ width }}> {children} </viewportContext.Provider> ); };
const useViewport = () => { const { width } = React.useContext(viewportContext); return { width }; }
export { ViewportProvider, useViewport } 2. index.tsx import { ViewportProvider } from './utils/viewportContext.tsx' <ViewportProvider> <RouterProvider router={router} /> </ViewportProvider> 3. 页面中使用 import { lazy } from "react" const PcHome = lazy(() => import('./pc.tsx')) const PhoneHome = lazy(() => import('./phone.tsx')) import { useViewport } from "../../utils/viewportContext.tsx" const Home = () => { const { width } = useViewport() const breakpoint = 720 return width < breakpoint ? <PhoneHome /> : <PcHome /> } export default Home 标签:React,const,Context,Hooks,react,width,window,tsx,import From: https://www.cnblogs.com/zscxy/p/17921730.html