3.19
项目构思 + leetcode算法题
今天开始打算实现自己的一个想法,做一个旅游景点讲解器的软件,打算使用TS+React,并且希望实现响应式布局满足现在不同屏幕尺寸的电子产品(ipad,手机,智能手表)的使用。上网搜索了资料,发现相关内容的网页基本为0,软件商店中有几款同功能软件,下载了下载量最多的一款,发现样式好看,不过使用起来较为繁琐,并且所有讲解都需要付钱,所以软件功能决定主要为讲解,可以购买讲解和发布讲解,有人购买,发布讲解的人会有金币(可提现),发布者可自行设定价格,可以有前30s免费试听。完成了页面大致设计,搜索相关技术资料。
响应式布局
1、媒体查询:@media
2、innerwidth:
// 根据用户设备的窗口宽度,但调整宽度大小时,未解决宽度值的更新问题,可能会渲染错误的组件 const MyComponent = () => { //当前窗口宽度 const width = window.innerWidth; // 临界值 const breakpoint = 620; // 宽度小于620时渲染手机组件,反之桌面组件 return width < breakpoint ? <MobileComponent /> : <DestopComponent />; }
3、Hooks+resize
//监听resize事件,触发useEffect改变数据 const MyComponent = () => { const [width, setWidth] = React.useState(window.innerWidth); //每次useEffect是独立的render React.useEffect(() => { const handleWindowResize = () => setWidth(window.innerwidth); window.addEventListener("resize", handleWindowResize); return () => window.removeEventListener("resize", handleWindowResize); }, []); return { width }; }
4、useViewport
//自定义React Hooks,能够将组件、函数最大程度的复用 const MyComponent = () => { const { width } = useViewport(); const breakpoint = 620; return width < breakpoint ? <MobileComponent /> : <DestopComponent />; } //存在性能问题,响应式布局影响的是多个组件,若是在多处使用useViewport,这将浪费性能。
5、Hooks+Context
//新建一个新的文件viewportContext,在这其中能够存储当前窗口大小的状态以及计算逻辑 const viewportContext = React.creatContext({}); const ViewportProvider = ({ children }) => { //在Hooks中,声明