使用React重新调整浏览器的渲染视图

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


背景

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


这是我的应用程序:


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上面的Pinterest示例中的):


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

});

有没有更“反应”的方式来做到这一点?


慕桂英546537
浏览 734回答 3
3回答

qq_遁去的一_1

使用React Hooks:您可以定义一个自定义的Hook来监听window resize事件,如下所示:import React, { useLayoutEffect, useState } from 'react';function useWindowSize() {&nbsp; const [size, setSize] = useState([0, 0]);&nbsp; useLayoutEffect(() => {&nbsp; &nbsp; function updateSize() {&nbsp; &nbsp; &nbsp; setSize([window.innerWidth, window.innerHeight]);&nbsp; &nbsp; }&nbsp; &nbsp; window.addEventListener('resize', updateSize);&nbsp; &nbsp; updateSize();&nbsp; &nbsp; return () => window.removeEventListener('resize', updateSize);&nbsp; }, []);&nbsp; return size;}function ShowWindowDimensions(props) {&nbsp; const [width, height] = useWindowSize();&nbsp; return <span>Window size: {width} x {height}</span>;}这样做的好处是逻辑被封装,您可以在要使用窗口大小的任何位置使用此Hook。使用React类:您可以在componentDidMount中进行监听,类似于该组件,它仅显示窗口尺寸(如<span>Window size: 1024 x 768</span>):import React from 'react';class ShowWindowDimensions extends React.Component {&nbsp; state = { width: 0, height: 0 };&nbsp; render() {&nbsp; &nbsp; return <span>Window size: {this.state.width} x {this.state.height}</span>;&nbsp; }&nbsp; updateDimensions = () => {&nbsp; &nbsp; this.setState({ width: window.innerWidth, height: window.innerHeight });&nbsp; };&nbsp; componentDidMount() {&nbsp; &nbsp; window.addEventListener('resize', this.updateDimensions);&nbsp; }&nbsp; componentWillUnmount() {&nbsp; &nbsp; window.removeEventListener('resize', this.updateDimensions);&nbsp; }}

守着一只汪

我只想根据此答案提供她的解决方案的修改版本,而无需jQuery。var WindowDimensions = React.createClass({&nbsp; &nbsp; render: function() {&nbsp; &nbsp; &nbsp; &nbsp; return <span>{this.state.width} x {this.state.height}</span>;&nbsp; &nbsp; },&nbsp; &nbsp; updateDimensions: function() {&nbsp; &nbsp; var w = window,&nbsp; &nbsp; &nbsp; &nbsp; d = document,&nbsp; &nbsp; &nbsp; &nbsp; documentElement = d.documentElement,&nbsp; &nbsp; &nbsp; &nbsp; body = d.getElementsByTagName('body')[0],&nbsp; &nbsp; &nbsp; &nbsp; width = w.innerWidth || documentElement.clientWidth || body.clientWidth,&nbsp; &nbsp; &nbsp; &nbsp; height = w.innerHeight|| documentElement.clientHeight|| body.clientHeight;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({width: width, height: height});&nbsp; &nbsp; &nbsp; &nbsp; // if you are using ES2015 I'm pretty sure you can do this: this.setState({width, height});&nbsp; &nbsp; },&nbsp; &nbsp; componentWillMount: function() {&nbsp; &nbsp; &nbsp; &nbsp; this.updateDimensions();&nbsp; &nbsp; },&nbsp; &nbsp; componentDidMount: function() {&nbsp; &nbsp; &nbsp; &nbsp; window.addEventListener("resize", this.updateDimensions);&nbsp; &nbsp; },&nbsp; &nbsp; componentWillUnmount: function() {&nbsp; &nbsp; &nbsp; &nbsp; window.removeEventListener("resize", this.updateDimensions);&nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP