最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.innerWidth in real time - Stack Overflow

programmeradmin4浏览0评论

I'm in need of getting the width of the browser when i resize the browser in real time. So far i've found a solution which gives the width but it's not in real time. The value is updated only after i refresh the web page. How can i get the value as i resize the browser.

My approach

render() {

var windowWidth = window.innerWidth;

return (

      <div className="body_clr">

        {windowWidth}

      </div>

)
}

This solution works if i refresh the page. But i want to get the width as i resize because i have to execute a function at a specific screen size.

I'm in need of getting the width of the browser when i resize the browser in real time. So far i've found a solution which gives the width but it's not in real time. The value is updated only after i refresh the web page. How can i get the value as i resize the browser.

My approach

render() {

var windowWidth = window.innerWidth;

return (

      <div className="body_clr">

        {windowWidth}

      </div>

)
}

This solution works if i refresh the page. But i want to get the width as i resize because i have to execute a function at a specific screen size.

Share Improve this question asked Aug 8, 2018 at 10:24 CraZyDroiDCraZyDroiD 7,10533 gold badges106 silver badges195 bronze badges 1
  • 1 stackoverflow./questions/19014250/… – brk Commented Aug 8, 2018 at 10:27
Add a ment  | 

2 Answers 2

Reset to default 9

Here's a way to do this:

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

  ponentDidMount() {
    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);

Working CodeSandbox here.

You can use event listeners:

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

发布评论

评论列表(0)

  1. 暂无评论