如何在ReactJS中获得视口高度?在正常的JavaScript中使用

window.innerHeight()

但是使用ReactJS,我不确定如何获得这些信息。我的理解是

ReactDOM.findDomNode()

仅适用于已创建的组件。然而,对于文档或body元素,情况并非如此,它们可以为我提供窗口的高度。


当前回答

// just use (useEffect). every change will be logged with current value
import React, { useEffect } from "react";

export function () {
  useEffect(() => {
    window.addEventListener('resize', () => {
      const myWidth  = window.innerWidth;
      console.log('my width :::', myWidth)
   })
  },[window])

  return (
    <>
      enter code here
   </>
  )
}

其他回答

保持当前尺寸状态的简单方法,即使在窗口调整大小后:

//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来获取当前视口的高度。

正如你在这里看到的

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}

我建议使用useSyncExternalStore

import { useSyncExternalStore } from "react";

const store = {
  size: {
    height: undefined,
    width: undefined
  }
};

export default function ChatIndicator() {
  const { height, width } = useSyncExternalStore(subscribe, getSnapshot);
  return (
    <h1>
      {width} {height}
    </h1>
  );
}

function getSnapshot() {
  if (
    store.size.height !== window.innerHeight ||
    store.size.width !== window.innerWidth
  ) {
    store.size = { height: window.innerHeight, width: window.innerWidth };
  }
  return store.size;
}

function subscribe(callback) {
  window.addEventListener("resize", callback);
  return () => {
    window.removeEventListener("resize", callback);
  };
}

如果你想试试:https://codesandbox.io/s/vibrant-antonelli-5cecpm

React原生web有一个useWindowDimensions钩子,可以使用:

    import { useWindowDimensions } from "react-native";
    const dimensions = useWindowDimensions()