javascript - 如何在服务器端渲染期间检查窗口/ block 宽度?

标签 javascript reactjs server-side-rendering

我有带有服务器端渲染的 React 应用程序。我在我的组件中使用窗口对象以获得窗口宽度并将元素放置在页面的中心。当我使用 ssr 时,我在控制台中收到错误消息,提示 window is not defined

如何消除此错误或如何获取窗口或 block 宽度并在渲染期间使用它? 这是我的组件的代码:

import React, { Component } from 'react';
import autoBind from 'react-autobind';

import SectionBackground from '../SectionBackground';

import Styles from './styles.scss';

export default class Section extends Component {
  constructor(props) {
    super(props);
    autoBind(this);
    this.state = {     
      windowWidth: 0,
      circleSecondLine: 0,
      circleThirdLine: 0,
    };
  }

  componentDidMount() {       
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  setCenterPosition() {    
     return this.state.width ? this.state.width / 2 : window.innerWidth / 2;
  }

  setLine() {
    let lineVPosiotion = 0;
    const { innerWidth } = window;
    if (innerWidth <= 768) {
      lineVPosiotion = 62;
    } else if (innerWidth <= 1023) {
      lineVPosiotion = 200;
    } else {
      lineVPosiotion = 300;
    }
    const coords = `M${this.state.width},0 v${lineVPosiotion}`;
    return coords;
  }

  handleResize() {
    this.setState({
      windowWidth: window.innerWidth,
    });
    this.setLine();  
  }

  render() {
    const sectionTemplate = {       
      setLine: this.setChatLine,     
      setCenterCircle: this.setCenterPosition,
    };
    return (
      <div className={Styles['anim-background']} ref={this.ref}>
        <SectionBackground {...sectionTemplate} />
      </div>
    );
  }
}

最佳答案

当您在服务器端运行代码时,它实际上并不知道窗口或文档。您需要全局注册窗口。为此,您可以在 package.json 的启动脚本中包含 jsdom-global/register,并且在启动服务器之前,您可以确保该窗口实例在全局范围内可用。

"start": "jsdom-global/register node ./dist/server"

首先安装以下包:

"jsdom": "11.11.0", "jsdom-global": "3.0.2"

希望这能奏效!

关于javascript - 如何在服务器端渲染期间检查窗口/ block 宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51282140/

相关文章:

javascript - 在破坏数组时如何阻止 Eclipse 在列上对齐?

javascript - 如何在鼠标位置插入一个div?

javascript - React/MUI Popover 使用 anchorPosition 定位不正确

ruby-on-rails - 引用错误 : navigator is not defined using ReactJS on Ruby on Rails server side rendering

angular - (Angular 6)Angular Universal - 不等待内容 API 调用

javascript - 读取php中的JS变量

javascript - @font-face 无法正常工作的问题

javascript - ant-d 中如何获取上传文件的文件路径?

javascript - react - 到达特定部分时停止滚动

javascript - Angular Universal Server Side Rendering 将返回更多根据请求呈现的 HTML