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

window.innerHeight()

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

ReactDOM.findDomNode()

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


当前回答

通过在useCallback中包装getWindowDimensions函数,我对代码进行了轻微的更新

import { useCallback, useLayoutEffect, useState } from 'react';

export default function useWindowDimensions() {

    const hasWindow = typeof window !== 'undefined';

    const getWindowDimensions = useCallback(() => {
        const windowWidth = hasWindow ? window.innerWidth : null;
        const windowHeight = hasWindow ? window.innerHeight : null;

        return {
            windowWidth,
            windowHeight,
        };
    }, [hasWindow]);

    const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

    useLayoutEffect(() => {
        if (hasWindow) {
            function handleResize() {
                setWindowDimensions(getWindowDimensions());
            }

            window.addEventListener('resize', handleResize);
            return () => window.removeEventListener('resize', handleResize);
        }
    }, [getWindowDimensions, hasWindow]);

    return windowDimensions;
}

其他回答

使用钩子(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来获取当前视口的高度。

正如你在这里看到的

用一点打字稿

import { useState, useEffect } from 'react'; interface WindowDimentions { width: number; height: number; } function getWindowDimensions(): WindowDimentions { const { innerWidth: width, innerHeight: height } = window; return { width, height }; } export default function useWindowDimensions(): WindowDimentions { const [windowDimensions, setWindowDimensions] = useState<WindowDimentions>( getWindowDimensions() ); useEffect(() => { function handleResize(): void { setWindowDimensions(getWindowDimensions()); } window.addEventListener('resize', handleResize); return (): void => window.removeEventListener('resize', handleResize); }, []); return windowDimensions; }

添加这个是为了多样性和干净的方法。

此代码使用函数式方法。我已经使用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>
    </>
  );
}

我发现了一个简单的组合QoP和speckledcarp的答案,使用React Hooks和调整大小功能,代码行数略少:

const [width, setWidth]   = useState(window.innerWidth);
const [height, setHeight] = useState(window.innerHeight);
const updateDimensions = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
}
useEffect(() => {
    window.addEventListener("resize", updateDimensions);
    return () => window.removeEventListener("resize", updateDimensions);
}, []);

哦,是的,确保resize事件是双引号,而不是单引号。这一点让我有点不安;)

@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's short</p>;
    else return <p>It's not short</p>;
}

export default withWindowDimensions(MyComponent);

你也可以“堆叠”hoc,如果你有另一个你需要使用,例如withthrouter (withWindowDimensions(MyComponent))

编辑:我现在会用React钩子(上面的例子),因为它们解决了hoc和类的一些高级问题