React Server Side Rendering - addEventListener



我有一个服务器端渲染反应应用程序(因为我也需要Facebook Seo(。

我的应用程序的一部分需要获取 window.innerWidth。

我已经搜索了很长时间,其中大多数都说您在服务器端找不到窗口,因此您还需要在客户端进行渲染

我不确定事情是如何工作的,我有组件挂载,但我的窗口宽度永远是 0。

服务器渲染后,我们的捆绑包.js将启动,客户端的窗口将正常工作吗?怎么还是0?

state = {
windowWidth: 0
}
handleResize(){
this.setState({windowWidth: window.innerWidth});
}
componentDidMount () {
window.addEventListener('resize', this.handleResize);
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
}
render() {
return (<div>{this.state.windowWidth}</div>)
}

问题是您附加了一个函数以将新宽度设置为"调整大小"侦听器,这意味着只有当您调整屏幕大小时,新宽度才会添加到状态中。您需要在componentDidMount内设置宽度,然后在安装时将其宽度设置为宽度。

沙盒

法典:

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
windowWidth: 0
};
}
handleResize = () => {
this.setState({ windowWidth: window.innerWidth });
};
componentDidMount() {
this.setState({ windowWidth: window.innerWidth });
window.addEventListener("resize", this.handleResize);
}
componentWillUnmount() {
window.removeEventListener("resize", this.handleResize);
}
render() {
return (
<div>{this.state.windowWidth && <p>{this.state.windowWidth}</p>}</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

最新更新