React でブラウザのサイズ変更時にビューを再レンダリングする 質問する

React でブラウザのサイズ変更時にビューを再レンダリングする 質問する

ブラウザウィンドウのサイズが変更されたときに、React でビューを再レンダリングするにはどうすればよいですか?

背景

ページ上に個別にレイアウトしたいブロックがいくつかありますが、ブラウザウィンドウが変更されたときにも更新されるようにしたいです。最終的な結果は次のようになります。ベン・ホランドのPinterest レイアウトですが、jQuery だけでなく React を使用して記述されています。まだ道のりは遠いです。

コード

これが私のアプリです:

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')
)

次に、Blockコンポーネント (Pin上記の Pi​​nterest の例の に相当) を作成します。

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

および以下のリスト/コレクション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>
    );
  }
});

質問

jQuery のウィンドウサイズ変更を追加する必要がありますか? その場合、どこに追加しますか?

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

これをもっと「React」的に行う方法はありますか?

ベストアンサー1

React Hooks の使用:

resize次のように、ウィンドウ イベントをリッスンするカスタム フックを定義できます。

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

ここでの利点は、ロジックがカプセル化されており、ウィンドウ サイズを使用する場所ならどこでもこのフックを使用できることです。

React クラスの使用:

ウィンドウの寸法を表示するだけの次のコンポーネントのようなものを、componentDidMount でリッスンできます ( など<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);
  }
}

おすすめ記事