javascript - window.innerWidth 实时
问题描述
当我实时调整浏览器大小时,我需要获取浏览器的宽度。到目前为止,我找到了一个给出宽度但不是实时的解决方案。只有在我刷新网页后才会更新该值。我如何在调整浏览器大小时获取值。
我的方法
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 。
推荐阅读
- php - 如何在 Laravel 5.8 中正确翻译激活邮件?
- html5-canvas - 如何使用 Chart.js 为每个数据集设置不同的图例数据样式?
- python - 如何停止使用记事本打开 .whl 文件?
- c# - EDMX 文件和数据库中的更改
- javascript - 验证具有相同名称[]和不同行类别的输入
- google-apps-script - 我需要一个谷歌脚本在谷歌表格中运行以删除空白单元格右侧的单元格
- r - 更改堆叠条形图中的颜色
- c# - webservice WCF 上的 maxRequestLength 已超出
- python - Python(熊猫):基于两列删除重复项,在另一列中保持行与标志
- typescript - 带有包罗万象的道具的可能递归对象的打字稿接口