Skip to content

Instantly share code, notes, and snippets.

@riskers
Last active January 6, 2022 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riskers/524811d980ca2e6cb8f022e4ee9e44e6 to your computer and use it in GitHub Desktop.
Save riskers/524811d980ca2e6cb8f022e4ee9e44e6 to your computer and use it in GitHub Desktop.
自定义 React Hook - useDevice (判断设备尺寸)
const App = () => {
const device = useDevice();
return <div className={getClassName(device)}>
Test
</div>
}
import { useWindowWidth } from "@react-hook/window-size";
import { useEffect } from "react";
import { useRafState } from "react-use";
export const PHONE_SIZE = 320;
export const IPAD_SIZE = 680;
export const PC_SIZE = 860;
export const BIG_PC_SIZE = 1300;
interface IDevice {
isPhone: boolean;
isPad: boolean;
isPC: boolean;
isBigPC: boolean;
}
const checkDevice = (windowWidth: number) => {
let isPhone = false,
isPad = false,
isPC = false,
isBigPC = false;
if (windowWidth >= PHONE_SIZE && windowWidth < IPAD_SIZE) isPhone = true;
if (windowWidth >= IPAD_SIZE && windowWidth < PC_SIZE) isPad = true;
if (windowWidth >= PC_SIZE && windowWidth < BIG_PC_SIZE) isPC = true;
if (windowWidth >= BIG_PC_SIZE) isBigPC = true;
return {
isPhone,
isPad,
isPC,
isBigPC,
};
};
export const getClassName = (device: IDevice): string => {
if (device.isPhone) return "phone";
if (device.isPad) return "pad";
if (device.isPC) return "pc";
if (device.isBigPC) return "bpc";
return "";
};
export const useDevice = () => {
// 使用 useState 也可以
const [state, setState] = useRafState<IDevice>({
isPhone: false,
isPad: false,
isPC: false,
isBigPC: false,
});
// 监听 window width
const windowWidth = useWindowWidth({ leading: true, wait: 100 });
useEffect(() => {
const deviceState = checkDevice(windowWidth);
setState(deviceState);
}, [windowWidth]);
return state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment