使用 React 调整浏览器大小的重新渲染视图 [英] Rerender view on browser resize with React

查看:117
本文介绍了使用 React 调整浏览器大小的重新渲染视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在调整浏览器窗口大小时让 React 重新渲染视图?

背景

我想在页面上单独布局一些块,但是我也希望它们在浏览器窗口更改时更新.最终的结果将类似于 Ben Holland 的 Pinterest 布局,但不仅仅是使用 jQuery 编写的 React.我还有很长的路要走.

代码

这是我的应用:

var MyApp = React.createClass({//http是否从服务器获取loadBlocksFromServer: function() {$.ajax({网址:this.props.url,数据类型:'json',mimeType: 'textPlain',成功:功能(数据){this.setState({data: data.events});}.绑定(这个)});},getInitialState:函数(){返回{数据:[]};},componentWillMount:函数(){this.loadBlocksFromServer();},渲染:函数(){返回 (<div><块数据={this.state.data}/>

);}});React.renderComponent(<MyApp url="url_here"/>,document.getElementById('view'))

然后我有 Block 组件(相当于上面 Pinterest 示例中的 Pin):

var Block = React.createClass({渲染:函数(){返回 (<div class="dp-block" style={{left: this.props.top, top: this.props.left}}><h2>{this.props.title}</h2><p>{this.props.children}</p>

);}});

Blocks的列表/集合:

var Blocks = React.createClass({渲染:函数(){//我暂时得到了分配随机位置的代码//查看下面的函数内部...var blockNodes = this.props.data.map(function (block) {//临时随机位置var topOffset = Math.random() * $(window).width() + 'px';var leftOffset = Math.random() * $(window).height() + 'px';return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;});返回 (<div>{blockNodes}</div>);}});

问题

我应该添加 jQuery 的窗口大小调整吗?如果有,在哪里?

$( window ).resize(function() {//重新渲染组件});

是否有更React"的方式来做到这一点?

解决方案

使用 React Hooks:

您可以定义一个自定义 Hook 来监听窗口 resize 事件,如下所示:

import React, { useLayoutEffect, useState } from 'react';函数 useWindowSize() {const [size, setSize] = useState([0, 0]);useLayoutEffect(() => {函数更新大小(){setSize([window.innerWidth, window.innerHeight]);}window.addEventListener('resize', updateSize);更新大小();返回 () =>window.removeEventListener('resize', updateSize);}, []);退货尺寸;}函数 ShowWindowDimensions(props) {const [宽度,高度] = useWindowSize();返回<span>窗口大小:{width} x {height}</span>;}

这里的好处是逻辑被封装了,你可以在任何你想使用窗口大小的地方使用这个Hook.

使用 React 类:

你可以在 componentDidMount 中监听,类似这个只显示窗口尺寸的组件(比如 Window size: 1024 x 768):

从'react'导入React;类 ShowWindowDimensions 扩展 React.Component {状态 = { 宽度:0,高度:0 };使成为() {返回<span>窗口大小:{this.state.width} x {this.state.height}</span>;}updateDimensions = () =>{this.setState({ width: window.innerWidth, height: window.innerHeight });};componentDidMount() {window.addEventListener('resize', this.updateDimensions);}componentWillUnmount() {window.removeEventListener('resize', this.updateDimensions);}}

How can I get React to re-render the view when the browser window is resized?

Background

I have some blocks that I want to layout individually on the page, however I also want them to update when the browser window changes. The very end result will be something like Ben Holland's Pinterest layout, but written using React not just jQuery. I’m still a way off.

Code

Here’s my app:

var MyApp = React.createClass({
  //does the http get from the server
  loadBlocksFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      mimeType: 'textPlain',
      success: function(data) {
        this.setState({data: data.events});
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentWillMount: function() {
    this.loadBlocksFromServer();

  },    
  render: function() {
    return (
        <div>
      <Blocks data={this.state.data}/>
      </div>
    );
  }
});

React.renderComponent(
  <MyApp url="url_here"/>,
  document.getElementById('view')
)

Then I have the Block component (equivalent to a Pin in the above Pinterest example):

var Block = React.createClass({
  render: function() {
    return (
        <div class="dp-block" style={{left: this.props.top, top: this.props.left}}>
        <h2>{this.props.title}</h2>
        <p>{this.props.children}</p>
        </div>
    );
  }
});

and the list/collection of Blocks:

var Blocks = React.createClass({

  render: function() {

    //I've temporarily got code that assigns a random position
    //See inside the function below...

    var blockNodes = this.props.data.map(function (block) {   
      //temporary random position
      var topOffset = Math.random() * $(window).width() + 'px'; 
      var leftOffset = Math.random() * $(window).height() + 'px'; 
      return <Block order={block.id} title={block.summary} left={leftOffset} top={topOffset}>{block.description}</Block>;
    });

    return (
        <div>{blockNodes}</div>
    );
  }
});

Question

Should I add jQuery’s window resize? If so, where?

$( window ).resize(function() {
  // re-render the component
});

Is there a more "React" way of doing this?

解决方案

Using React Hooks:

You can define a custom Hook that listens to the window resize event, something like this:

import React, { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

function ShowWindowDimensions(props) {
  const [width, height] = useWindowSize();
  return <span>Window size: {width} x {height}</span>;
}

The advantage here is the logic is encapsulated, and you can use this Hook anywhere you want to use the window size.

Using React classes:

You can listen in componentDidMount, something like this component which just displays the window dimensions (like <span>Window size: 1024 x 768</span>):

import React from 'react';

class ShowWindowDimensions extends React.Component {
  state = { width: 0, height: 0 };
  render() {
    return <span>Window size: {this.state.width} x {this.state.height}</span>;
  }
  updateDimensions = () => {
    this.setState({ width: window.innerWidth, height: window.innerHeight });
  };
  componentDidMount() {
    window.addEventListener('resize', this.updateDimensions);
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.updateDimensions);
  }
}

这篇关于使用 React 调整浏览器大小的重新渲染视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆