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

JavaScript

伽罗GreenNear

2020-03-10

调整浏览器窗口大小时,如何让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
});

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

第440篇《使用React重新调整浏览器的渲染视图》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
樱小胖 2020.03.10

因此,更好的方法是使用CSS或JSON文件数据中的数据,然后使用this.state({width:“ some value”,height:“ some value”});设置新状态。或编写代码,在自己的工作中使用宽屏数据的数据(如果您希望响应显示图像)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android