useEffect 钩子不会在方向改变时触发

mar*_*ark 5 javascript reactjs react-hooks

我试图仅在移动横向模式下更改容器的高度。我正在开发人员工具中尝试交换移动设备的方向,但它仅适用于第一次渲染。我是反应钩子的新手,所以不确定我是否正确实现了它。

我的想法是,我正在测试一旦处于横向状态,如果在移动设备上,高度小于 450px(这是我为 if 语句所做的检查)

有人能给我指出正确的方向吗?

谢谢!

const bikeImageHeight = () => {
    const windowViewportHeight = window.innerHeight;
    const isLandscape = window.orientation === 90 || window.orientation === -90;
    let bikeImgHeight = 0;

    if (windowViewportHeight <= 450 && isLandscape) {
      bikeImgHeight = windowViewportHeight - 50;
    }

    return bikeImgHeight;
  };

  useEffect(() => {
    bikeImageHeight();

    window.addEventListener("resize", bikeImageHeight);

    return () => {
      window.removeEventListener("resize", bikeImageHeight);
    };
  }, []);
Run Code Online (Sandbox Code Playgroud)

pet*_*eld 6

预计钩子useEffect不会在方向改变时触发。它定义了一个回调,该回调将在组件重新渲染时触发。接下来的问题是当屏幕方向改变时如何触发重新渲染。当组件的 props 或状态发生变化时,就会发生重新渲染。

让我们利用另一个相关的 stackoverflow 答案来构建一个useWindowDimensions钩子。这允许我们将窗口大小作为组件状态挂钩,因此任何更改都将导致重新渲染。

useWindowDimensions.js

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;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以在组件中使用该钩子。就像是:

BikeImage.js

import React from 'react'
import useWindowDimensions from './useWindowDimensions'

export default () => {
  const windowDimensions = useWindowDimensions();

  // Define these helper functions as you like
  const width = getImageWidth(windowDimensions.width)
  const height = getImageHeight(windowDimensions.height)

  // AppImage is a component defined elsewhere which takes 
  // at least width, height and src props
  return <AppImage  width={width} height={height} src="..." .../>
}
Run Code Online (Sandbox Code Playgroud)