繁体   English   中英

window.innerWidth实时

[英]window.innerWidth in real time

实时调整浏览器大小时,我需要获得浏览器的宽度。 到目前为止,我已经找到了给出宽度的解决方案,但是它不是实时的。 该值仅在刷新网页后才更新。 调整浏览器大小时,如何获得该值。

我的方法

render() {

var windowWidth = window.innerWidth;

return (

      <div className="body_clr">

        {windowWidth}

      </div>

)
}

如果我刷新页面,则此解决方案有效。 但是我想在调整大小时获得宽度,因为我必须以特定的屏幕尺寸执行功能。

这是一种方法:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      height: 0,
      width: 0
    };

    window.addEventListener("resize", this.update);
  }

  componentDidMount() {
    this.update();
  }

  update = () => {
    this.setState({
      height: window.innerHeight,
      width: window.innerWidth
    });
  };

  render() {
    return (
      <React.Fragment>
        <p>height: {this.state.height}</p>
        <p>width: {this.state.width}</p>
      </React.Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

在这里使用 CodeSandbox。

您可以使用事件监听器

 window.addEventListener("resize", function() { return window.innerWidth; }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM