代码之家  ›  专栏  ›  技术社区  ›  deadcoder0904

如何使用React钩子'UseWindowsSize'在MobX存储中初始化窗口大小?

  •  0
  • deadcoder0904  · 技术社区  · 4 年前

    我有 win() 内部功能 FrameItStore 它回来了 window.innerWidth & window.innerHeight .但它并不总是在窗口大小改变时更新。

    FrameItStore。ts

    import { makeObservable, observable, action, computed } from 'mobx'
    
    export class FrameItStore implements IFrameItStore {
      constructor() {
        makeObservable(this, {
          win: observable,
        })
      }
    
      win(): Window {
        return {
          width: window.innerWidth,
          height: window.innerHeight,
        }
      }
    }
    
    export const config = new FrameItStore()
    

    所以我想用窗户大小的钩子 https://www.npmjs.com/package/@react-hook/window-size 获取更新的维度。

    问题是我不知道如何初始化 赢() 函数的钩子值,因为钩子只能在React组件中调用?

    我该怎么做?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Tholle    4 年前

    由于将窗口尺寸存储在React组件之外,因此如果愿意,也可以在React组件之外更新它们。

    实例

    import { makeObservable, observable, action } from 'mobx';
    
    export class FrameItStore implements IFrameItStore {
      win = {
        width: window.innerWidth,
        height: window.innerHeight
      };
    
      constructor() {
        makeObservable(this, {
          win: observable,
          updateWin: action.bound
        });
        
        // Update this.win every time the window resizes
        window.addEventListener("resize", this.updateWin);
      }
    
      updateWin() {
        this.win.width = window.innerWidth;
        this.win.height = window.innerHeight;
      }
      
      // If your FrameItStore won't live for the entire duration of the application,
      // you can call this method to remove the event listener.
      destroy() {
        window.removeEventListener("resize", this.updateWin);
      }
    }