由于将窗口尺寸存储在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);
}
}