如何解决如何使用 React Hook `useWindowSize` 来初始化 MobX Store 内的窗口大小?
我在 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()
所以我想使用 Window Size Hook → https://www.npmjs.com/package/@react-hook/window-size 来获取更新的尺寸。
问题是我不知道如何使用钩子值初始化 win()
函数,因为钩子只能在 React 组件中调用?
我该怎么做?
解决方法
由于您将窗口尺寸存储在 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。