Получить высоту видового экрана/окна в ReactJS
Как получить высоту видового экрана???
window.innerHeight()
Но с помощью reactjs я не уверен, как получить эту информацию. Я понимаю, что
ReactDOM.findDomNode()
работает только для созданных компонентов. Однако это не относится к элементу document или body, который может дать мне высоту окна.
Ответы
Ответ 1
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = {height: props.height};
}
componentWillMount(){
this.setState({height: window.innerHeight + 'px'});
}
render() {
// render your component...
}
}
Установите реквизит
AppComponent.propTypes = {
height:React.PropTypes.string
};
AppComponent.defaultProps = {
height:'500px'
};
высота видового экрана теперь доступна как {this.state.height} в шаблоне рендеринга
Ответ 2
Этот ответ похож на Jabran Saeed, за исключением того, что он также обрабатывает изменение размера окна. Я получил это отсюда.
constructor(props) {
super(props);
this.state = { width: 0, height: 0 };
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth, height: window.innerHeight });
}
Ответ 3
Использование крючков (Реакция 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>
);
}
Рабочий пример
Оригинальный ответ
window.innerHeight
же самое в React, вы можете использовать window.innerHeight
для получения текущей высоты области просмотра.
Как вы можете видеть здесь
Ответ 4
Я просто потратил какое-то серьезное время на то, чтобы разобраться с ситуациями React и прокруткой событий/позиций - так что для тех, кто все еще смотрит, вот что я нашел:
Высота просмотра может быть найдена с помощью window.innerHeight или с помощью document.documentElement.clientHeight. (Текущая высота видового экрана)
Высота всего документа (тела) может быть найдена с помощью window.document.body.offsetHeight.
Если вы пытаетесь найти высоту документа и знаете, когда попали в нижнюю часть - вот что я придумал:
if (window.pageYOffset >= this.myRefII.current.clientHeight && Math.round((document.documentElement.scrollTop + window.innerHeight)) < document.documentElement.scrollHeight - 72) {
this.setState({
trueOrNot: true
});
} else {
this.setState({
trueOrNot: false
});
}
}
(Мой навигатор был 72px в фиксированном положении, таким образом, -72, чтобы получить лучший свиток событий прокрутки)
Наконец, вот несколько команд прокрутки для console.log(), которые помогли мне разобраться в моей математике.
console.log('window inner height: ', window.innerHeight);
console.log('document Element client hieght: ', document.documentElement.clientHeight);
console.log('document Element scroll hieght: ', document.documentElement.scrollHeight);
console.log('document Element offset height: ', document.documentElement.offsetHeight);
console.log('document element scrolltop: ', document.documentElement.scrollTop);
console.log('window page Y Offset: ', window.pageYOffset);
console.log('window document body offsetheight: ', window.document.body.offsetHeight);
Уф! Надеюсь, это поможет кому-то!
Ответ 5
Ответ @speckledcarp хорош, но может быть утомительным, если вам нужна эта логика в нескольких компонентах. Вы можете изменить его как HOC (компонент более высокого порядка), чтобы облегчить повторное использование этой логики.
withWindowDimensions.jsx
import React, { Component } from "react";
export default function withWindowDimensions(WrappedComponent) {
return class extends Component {
state = { width: 0, height: 0 };
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener("resize", this.updateWindowDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateWindowDimensions);
}
updateWindowDimensions = () => {
this.setState({ width: window.innerWidth, height: window.innerHeight });
};
render() {
return (
<WrappedComponent
{...this.props}
windowWidth={this.state.width}
windowHeight={this.state.height}
isMobileSized={this.state.width < 700}
/>
);
}
};
}
Тогда в вашем основном компоненте:
import withWindowDimensions from './withWindowDimensions.jsx';
class MyComponent extends Component {
render(){
if(this.props.isMobileSized) return <p>It short</p>;
else return <p>It not short</p>;
}
export default withWindowDimensions(MyComponent);
Вы также можете "сложить" HOC, если у вас есть другой, который вам нужно использовать, например, withRouter(withWindowDimensions(MyComponent))
Ответ 6
Ответы @speckledcarp и @Jamesl оба великолепны. В моем случае, однако, мне был нужен компонент, высота которого могла бы увеличить всю высоту окна, условно во время рендеринга... но вызов HOC в render()
повторно render()
все поддерево. BAAAD.
Кроме того, я не был заинтересован в получении значений в качестве реквизита, а просто хотел, чтобы родительский div
занимал всю высоту экрана (или ширину, или оба).
Итак, я написал родительский компонент, обеспечивающий полную высоту (и/или ширину) div. Boom.
Вариант использования:
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
Ответ 7
Вы также можете попробовать следующее:
constructor(props) {
super(props);
this.state = {height: props.height, width:props.width};
}
componentWillMount(){
console.log("WINDOW : ",window);
this.setState({height: window.innerHeight + 'px',width:window.innerWidth+'px'});
}
render() {
console.log("VIEW : ",this.state);
}