如何为我的应用程序中需要它的所有 React 组件提供窗口宽度?

所以我有这个钩子来返回windowWidth我的 App 组件。我将此称为Option #1。


import {useEffect, useState} from 'react';


function useWindowWidth() {


  const [windowWidth,setWindowWidth] = useState(window.innerWidth);


  useEffect(() => {


    function handleResize() {

      setWindowWidth(window.innerWidth);

    }


    window.addEventListener('resize', handleResize);

    return () => window.removeEventListener('resize', handleResize);

  }, []);


  return windowWidth;

}


export default useWindowWidth;

现在我基本上在每个依赖窗口宽度渲染的组件上使用它,例如:


function Component(props) {

  const windowWidth = useWindowWidth();

  return(

    // RETURN SOMETHING BASED ON WINDOW WIDTH

  );

}

由于钩子有一个事件监听器resize,组件即使在窗口调整大小后也能保持响应。


但我担心我正在为每个使用该钩子的组件附加一个新的侦听器,这可能会在某些时候减慢速度。我想过其他方法:


选项#2


我useWindowWidth()只在顶级组件中使用了一次钩子,例如<App/>,我将windowWidth通过上下文在链中提供值。


喜欢:


function App() {

  const windowWidth = useWindowWidth();

  return(

    <WindowWidthContext.Provider value={windowWidth}>

      <Rest_of_the_app/>

    </WindowWidthContext.Provider>

  );

}

然后,每个需要它的组件都可以通过:


function Component() {

  const windowWidth = useContext(WindowWidthContext);

  return(

    // SOMETHING BASED ON WINDOW WIDTH

  );

}

问题


我是否对我正在resize使用选项 #1设置多个侦听器这一事实感到困扰?是选择2的好办法租期,提高该流?


人到中年有点甜
浏览 187回答 2
2回答

慕桂英3389331

我不确定添加和删除事件侦听器是否比设置和删除映射键更昂贵的操作,但也许以下内容会对其进行优化:const changeTracker = (debounceTime => {&nbsp; const listeners = new Map();&nbsp; const add = fn => {&nbsp; &nbsp; listeners.set(fn, fn);&nbsp; &nbsp; return () => listeners.delete(fn);&nbsp; };&nbsp; let debounceTimeout;&nbsp; window.addEventListener('resize', () => {&nbsp; &nbsp; clearTimeout(debounceTimeout);&nbsp; &nbsp; debounceTimeout = setTimeout(&nbsp; &nbsp; &nbsp; () => {&nbsp; &nbsp; &nbsp; &nbsp; const width=window.innerWidth;&nbsp; &nbsp; &nbsp; &nbsp; listeners.forEach(l => l(width))&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; debounceTime&nbsp; &nbsp; );&nbsp; });&nbsp; return add;})(200);function useWindowWidth() {&nbsp; const [windowWidth, setWindowWidth] = useState(&nbsp; &nbsp; () => window.innerWidth&nbsp; );&nbsp; useEffect(&nbsp; &nbsp; () =>//changeTracker returns a remove function&nbsp; &nbsp; &nbsp; changeTracker((width) =>&nbsp; &nbsp; &nbsp; &nbsp; setWindowWidth(width)&nbsp; &nbsp; &nbsp; ),&nbsp; &nbsp; []&nbsp; );&nbsp; return windowWidth;}

白猪掌柜的

如果您的窗口 with 被您提到的这么多组件使用,则您必须更喜欢使用context.&nbsp;如下所示:上下文适用于全球范围的应用。所以,#2这里是每个反应的完美选择。第一种方法#1可能适用于相同层次结构但最多 2-3 级的组件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript