前端精神小伙:React Hooks 响应式布局

253 阅读3分钟
原文链接: mp.weixin.qq.com

(给 前端大全加星标,提升前端技能 )

作者: 前端劝退师 公号 /  前端劝退师 (本文来自作者投稿)

前言

现在稍微大型的站点都会采用H5/PC端 并行,通过nignx获取浏览器的 UA信息来切换站点。

但这对于一些企业站点或人手不足的小型项目来说,就很难实现。

通过CSS媒体查询实现响应式布局,是主流方式。

但是,有时在 React 程序中,需要根据屏幕大小有条件地渲染不同的组件(写媒体查询太麻烦了,还不如另写组件),其实使用React Hooks,可以更灵活实现。

本文的实现来自:

Developing responsive layouts with React Hooks

1. 方案一:innerWidth

一个很简单粗略的方案,是个前端都知道:

const MyComponent = () => {  // 当前窗口宽度  const width = window.innerWidth;  // 邻介值  const breakpoint = 620;  // 宽度小于620时渲染手机组件,反之桌面组件  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;}

这个简单的解决方案肯定会起作用。根据用户设备的窗口宽度,我们可以呈现桌面视图或手机视图。

但是,当调整窗口大小时,未解决宽度值的更新问题,可能会渲染错误的组件。

2. 方案二:Hooks+resize

说着也简单,监听resize事件时,触发 useEffect改变数据。

const MyComponent = () => {  const [width, setWidth] = React.useState(window.innerWidth);  const breakpoint = 620;  React.useEffect(() => {    window.addEventListener("resize", () => setWidth(window.innerWidth));  }, []);  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;}

但精通Hooks的你,一定知道这里存在内存性能消耗问题: resize事件没移除!

优化版本:

const useViewport = () => {  const [width, setWidth] = React.useState(window.innerWidth);  React.useEffect(() => {    const handleWindowResize = () => setWidth(window.innerWidth);    window.addEventListener("resize", handleWindowResize);    return () => window.removeEventListener("resize", handleWindowResize);  }, []);  return { width };}

3. 方案三:构建useViewport

自定义React Hooks,可以将组件/函数最大程度的复用。构建一个也很简单:

const useViewport = () => {  const [width, setWidth] = React.useState(window.innerWidth);  React.useEffect(() => {    const handleWindowResize = () => setWidth(window.innerWidth);    window.addEventListener("resize", handleWindowResize);    return () => window.removeEventListener("resize", handleWindowResize);  }, []);  return { width };}

精简后的组件代码:

const MyComponent = () => {  const { width } = useViewport();  const breakpoint = 620;  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;}

但是这里还有另一个性能问题:

响应式布局影响的是多个组件,如果在多处使用useViewport,这将浪费性能。

这时就需要另一个React亲儿子: React Context(上下文) 来帮忙。

4.终极方案:Hooks+Context

我们将创建一个新的文件viewportContext,在其中可以存储当前视口大小的状态以及计算逻辑。

const viewportContext = React.createContext({});const ViewportProvider = ({ children }) => {  // 顺带监听下高度,备用  const [width, setWidth] = React.useState(window.innerWidth);  const [height, setHeight] = React.useState(window.innerHeight);  const handleWindowResize = () => {    setWidth(window.innerWidth);    setHeight(window.innerHeight);  }  React.useEffect(() => {    window.addEventListener("resize", handleWindowResize);    return () => window.removeEventListener("resize", handleWindowResize);  }, []);  return (    <viewportContext.Provider value={{ width, height }}>      {children}    </viewportContext.Provider>  );};const useViewport = () => {  const { width, height } = React.useContext(viewportContext);  return { width, height };}

紧接着,你需要在React根节点,确保已经包裹住了 App

const App = () => {  return (    <ViewportProvider>      <AppComponent />    </ViewportProvider>  );}

在往后的每次useViewport(),其实都只是共享 Hooks

const MyComponent = () => {  const { width } = useViewport();  const breakpoint = 620;  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;}

后记

github上面的响应式布局 hooks,都是大同小异的实现方式。

本文除了介绍React Hooks的响应式布局实现,还介绍了如何自定义 hooks与使用Context上下文,来复用,以达到性能最佳优化。

推荐阅读   点击标题可跳转

React Hooks异步操作二三事

React:useHooks小窍门

8 个问题带你进阶 React

觉得本文对你有帮助?请分享给更多人

关注「前端大全」加星标,提升前端技能

好文章,我在看❤️