react获取当前窗口宽高(hook方式)

使用useWindowSize

js方式使用

//引入  根据你自己的路径
import {useWindowSize} from '@/utils/hooks/useWindowSize.js';

const {width, height} = useWindowSize();

js方式定义

// An highlighted block
import { useState, useEffect } from 'react';

export const useWindowSize = () => {
  // 第一步:声明能够体现视口大小变化的状态
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  // 第二步:通过生命周期 Hook 声明回调的绑定和解绑逻辑
  useEffect(() => {
    const updateSize = () => setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
    window.addEventListener('resize', updateSize);
    return () => window.removeEventListener('resize', updateSize);
  }, []);

  return windowSize;
}

ts方式使用

import React from 'react'

import useWindowSize from './useWindowSize'

export default function Component() {
  const { width, height } = useWindowSize()

  return (
    <div>
      The current window dimensions are:{' '}
      <code>{JSON.stringify({ width, height })}</code>
    </div>
  )
}

ts方式定义

// An highlighted block
import { useEffect, useState } from 'react'

interface WindowSize {
  width: number
  height: number
}

function useWindowSize(): WindowSize {
  const [windowSize, setWindowSize] = useState<WindowSize>({
    width: 0,
    height: 0,
  })

  useEffect(() => {
    const handler = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      })
    }

    // Set size at the first client-side load
    handler()

    window.addEventListener('resize', handler)

    // Remove event listener on cleanup
    return () => {
      window.removeEventListener('resize', handler)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return windowSize
}

export default useWindowSize

部分收集自网络,侵删


版权声明:本文为weixin_44197210原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。