react Hooks+Context 实现响应式布局

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
 
 
posted @ 2023-12-22 15:36  卢老师不想编程  阅读(27)  评论(0编辑  收藏  举报