【发布时间】:2023-03-12 23:15:01
【问题描述】:
在我在 Gatsby 创建的网站上,我想在第一次渲染之前检查 DOM window.innerWidth 的大小。我想使用 innerWidth 的条件检查来决定网站应该如何呈现:作为桌面版或移动版。 一个简单的解决方法是在创建反应组件之前检查窗口的宽度,并在代码中进一步使用真/假值。它适用于开发版本,但... 情况是,在生产版本中,当我执行 gatsby build 时,控制台中出现错误:
failed Building static HTML for pages - 2.872s
ERROR #95312
"window" is not available during server-side rendering.
See our docs page for more info on this error: https://gatsby.dev/debug-html
> 30 | const sizeOfWindow = window.innerWidth;
我已经尝试使用 componentWillMount,它工作正常,但已被弃用并标记为不安全。 如果我检查 componentDidMount 中的 window.innerWidth 没有正确渲染。
我的代码:
interface IndexPageState {
isDesktop: boolean;
windowWidth: number;
}
class IndexPage extends React.Component<any, IndexPageState> {
constructor(props: any) {
super(props);
this.state = {
windowWidth: 0,
isDesktop: true,
};
}
componentWillMount(): void {
this.onResize();
}
onResize = () => {
if (!(this.state.windowWidth >= 769)) {
this.setState({ isDesktop: false });
} else {
this.setState({ isDesktop: true });
}
};
componentDidMount = () => {
this.setState({ windowWidth: window.innerWidth });
if (!(this.state.windowWidth >= 769)) {
this.setState({ isDesktop: false });
} else {
this.setState({ isDesktop: true });
}
window.addEventListener('resize', this.onResize);
};
componentWillUnmount = () => {
window.removeEventListener('resize', this.onResize);
};
render() {
const { isDesktop, windowWidth } = this.state;
return (
<>
<SEO title="Home" />
<div className={styles.App}>
【问题讨论】:
标签: javascript reactjs mobile gatsby