window.innerWidth 实时

Cra*_*oiD 2 javascript window reactjs

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

我的方法

render() {

var windowWidth = window.innerWidth;

return (

      <div className="body_clr">

        {windowWidth}

      </div>

)
}
Run Code Online (Sandbox Code Playgroud)

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

Col*_*rdo 8

这是一种方法:

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);
Run Code Online (Sandbox Code Playgroud)

在这里工作 CodeSandbox 。

  • 问题上有一个 `reactjs` 标签,所以我认为它可能会有所帮助。 (7认同)

Wai*_*mal 6

您可以使用事件监听器

window.addEventListener("resize", function() {
  return window.innerWidth;
});
Run Code Online (Sandbox Code Playgroud)