如何在ReactJS中获得视口高度?在正常的JavaScript中使用
window.innerHeight()
但是使用ReactJS,我不确定如何获得这些信息。我的理解是
ReactDOM.findDomNode()
仅适用于已创建的组件。然而,对于文档或body元素,情况并非如此,它们可以为我提供窗口的高度。
如何在ReactJS中获得视口高度?在正常的JavaScript中使用
window.innerHeight()
但是使用ReactJS,我不确定如何获得这些信息。我的理解是
ReactDOM.findDomNode()
仅适用于已创建的组件。然而,对于文档或body元素,情况并非如此,它们可以为我提供窗口的高度。
当前回答
保持当前尺寸状态的简单方法,即使在窗口调整大小后:
//set up defaults on page mount
componentDidMount() {
this.state = { width: 0, height: 0 };
this.getDimensions();
//add dimensions listener for window resizing
window.addEventListener('resize', this.getDimensions);
}
//remove listener on page exit
componentWillUnmount() {
window.removeEventListener('resize', this.getDimensions);
}
//actually set the state to the window dimensions
getDimensions = () => {
this.setState({ width: window.innerWidth, height: window.innerHeight });
console.log(this.state);
}
其他回答
使用钩子(React 16.8.0+)
创建一个useWindowDimensions钩子。
import { useState, useEffect } from 'react';
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return windowDimensions;
}
之后你就可以像这样在元件中使用它了
const Component = () => {
const { height, width } = useWindowDimensions();
return (
<div>
width: {width} ~ height: {height}
</div>
);
}
工作示例
原来的答案
在React中也是一样的,你可以使用window。innerHeight来获取当前视口的高度。
正如你在这里看到的
React原生web有一个useWindowDimensions钩子,可以使用:
import { useWindowDimensions } from "react-native";
const dimensions = useWindowDimensions()
你可以像这样创建自定义钩子:
import { useEffect, useState } from "react";
import { debounce } from "lodash";
const getWindowDimensions = () => {
const { innerWidth: width, innerHeight: height } = window;
return { width, height };
};
export function useWindowSize(delay = 0) {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
);
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions());
}
const debouncedHandleResize = debounce(handleResize, delay);
window.addEventListener("resize", debouncedHandleResize);
return () => window.removeEventListener("resize", debouncedHandleResize);
}, [delay]);
return windowDimensions;
}
@speckledcarp和@Jamesl的回答都很精彩。然而,在我的例子中,我需要一个组件,其高度可以扩展整个窗口高度,在呈现时有条件....但是在render()中调用HOC会重新渲染整个子树。很糟糕。
另外,我对获取作为道具的值不感兴趣,但只是想要一个父div,将占据整个屏幕的高度(或宽度,或两者)。
所以我写了一个父组件,提供了一个完整的高度(和/或宽度)div。
一个用例:
class MyPage extends React.Component {
render() {
const { data, ...rest } = this.props
return data ? (
// My app uses templates which misbehave badly if you manually mess around with the container height, so leave the height alone here.
<div>Yay! render a page with some data. </div>
) : (
<FullArea vertical>
// You're now in a full height div, so containers will vertically justify properly
<GridContainer justify="center" alignItems="center" style={{ height: "inherit" }}>
<GridItem xs={12} sm={6}>
Page loading!
</GridItem>
</GridContainer>
</FullArea>
)
下面是这个组件:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class FullArea extends Component {
constructor(props) {
super(props)
this.state = {
width: 0,
height: 0,
}
this.getStyles = this.getStyles.bind(this)
this.updateWindowDimensions = this.updateWindowDimensions.bind(this)
}
componentDidMount() {
this.updateWindowDimensions()
window.addEventListener('resize', this.updateWindowDimensions)
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions)
}
getStyles(vertical, horizontal) {
const styles = {}
if (vertical) {
styles.height = `${this.state.height}px`
}
if (horizontal) {
styles.width = `${this.state.width}px`
}
return styles
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth, height: window.innerHeight })
}
render() {
const { vertical, horizontal } = this.props
return (
<div style={this.getStyles(vertical, horizontal)} >
{this.props.children}
</div>
)
}
}
FullArea.defaultProps = {
horizontal: false,
vertical: false,
}
FullArea.propTypes = {
horizontal: PropTypes.bool,
vertical: PropTypes.bool,
}
export default FullArea
添加这个是为了多样性和干净的方法。
此代码使用函数式方法。我已经使用onresize而不是addEventListener,如在其他答案中提到的。
import { useState, useEffect } from "react";
export default function App() {
const [size, setSize] = useState({
x: window.innerWidth,
y: window.innerHeight
});
const updateSize = () =>
setSize({
x: window.innerWidth,
y: window.innerHeight
});
useEffect(() => (window.onresize = updateSize), []);
return (
<>
<p>width is : {size.x}</p>
<p>height is : {size.y}</p>
</>
);
}