ReactJs上没有定义获取窗口

时间:2015-09-12 06:20:51

标签: javascript reactjs fbjs

我在React上收到错误:"ReferenceError: window is not defined"

以下是我的代码:

import React from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import SignInMenu from './SignInMenu';
import UserMenu from './UserMenu';
import Navigation from '../Navigation';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';

@withStyles(styles)
class Header extends React.Component {

  constructor() {
    super();
    return {
      windowWidth: 0,
      windowHeight: 0
    };
  }

  componentDidMount() {
    this.setState({
      windowWidth: window.innerWidth,
      windowHeight: window.innerHeight
    });
  }

  render() {
     let windowWidth = this.state.windowWidth;
     let windowHeight = this.state.windowHeight;

     if (windowWidth < 1000) {
       let header = (<div>mobile</div>);
     }  else {
       let header = (<div>desktop</div>);
    }
  }

我正在尝试为桌面和移动设备呈现不同的视图,我刚刚开始使用React。我不确定我是否正确行事,在线跟踪一些指南并被困在这里。关于我做错了什么的任何想法?感谢

1 个答案:

答案 0 :(得分:2)

你的问题可能在你的构造函数中。

    constructor() {
      super();
      this.state = {
        windowWidth: 0,
        windowHeight: 0
      };
    }