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

标签 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>
    );
  }
}

最佳答案

我有一个调整大小的辅助组件,我可以将一个函数传递给它,它看起来像这样:

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 />);
    }
}

然后任何需要在调整大小上做某事的组件都可以像这样使用它:

<ResizeHelper onWindowResize={this.handleResize} />

您可能还需要在 componentDidMount 上调用一次传递的函数来设置 UI。由于 componentDidMount 和 componentWillUnmount 永远不会在服务器上被调用,所以这在我的同构应用程序中完美运行。

关于reactjs - React Isomorphic Rendering - 处理窗口调整大小事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40580424/

相关文章:

javascript - 我的 if 语句做错了什么?

javascript - Angular 2 是同构的吗? future 还会这样吗?

express - 在同构的reactjs中检测移动设备

javascript - React Router 链接渲染 #/代替/

javascript - 刷新页面时 session 丢失(Next、react、同构)

javascript - 当主体函数进行条件检查时,useEffect 钩子(Hook)应该返回什么?

javascript - async wait 返回 Promise 而不是值

javascript - 具有 Chakra UI 的 React-hook-form 在 NextJS 中不显示验证错误消息

javascript - 如何使用 React 删除表格中的一行?

node.js - 使用 webpack 中定义的 Alias 进行客户端 React 渲染但有问题