React Isomorphic Rendering - 处理窗口调整大小事件

Dra*_*anS 2 reactjs isomorphic-javascript

我想根据浏览器窗口的当前大小设置组件的状态.已使用服务器端呈现(React + Redux).我正在考虑使用Redux商店作为粘合剂 - 只是在调整大小时更新商店.有没有其他/更好的解决方案,不涉及Redux.谢谢.

class FocalImage extends Component {

  // won't work - the backend rendering is used
  // componentDidMount() {
  //  window.addEventListener(...);
  //}

  //componentWillUnmount() {
  //  window.removeEventListener('resize' ....);
  //}

  onresize(e) {
    //
  }

  render() {
    const {src, className, nativeWidth, nativeHeight} = this.props;
    return (
      <div className={cn(className, s.focalImage)}>
        <div className={s.imageWrapper}>
          <img src={src} className={_compare_ratios_ ? s.tall : s.wide}/>
        </div>
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ger 5

我有一个resize helper组件,我可以传递一个函数,如下所示:

class ResizeHelper extends React.Component {

    static propTypes = {
        onWindowResize: PropTypes.func,
    };

    constructor() {
        super();
        this.handleResize = this.handleResize.bind(this);
    }

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

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

    handleResize(event) {
        if ('function' === typeof this.props.onWindowResize) {
            // we want this to fire immediately the first time but wait to fire again
            // that way when you hit a break it happens fast and only lags if you hit another break immediately
            if (!this.resizeTimer) {
                this.props.onWindowResize(event);
                this.resizeTimer = setTimeout(() => {
                    this.resizeTimer = false;
                }, 250); // this debounce rate could be passed as a prop
            }
        }
    }

    render() {
        return (<div />);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后任何需要在调整大小时执行某些操作的组件都可以像这样使用它:

<ResizeHelper onWindowResize={this.handleResize} />
Run Code Online (Sandbox Code Playgroud)

您还可能需要在componentDidMount上调用传递的函数一次以设置UI.由于在服务器上永远不会调用componentDidMount和componentWillUnmount,因此在我的同构App中完美运行.