init commit
This commit is contained in:
23
src/hooks/useIsMobile.ts
Normal file
23
src/hooks/useIsMobile.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useMediaQuery(query: string): boolean {
|
||||
const [matches, setMatches] = useState(() => {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return window.matchMedia(query).matches;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const mql = window.matchMedia(query);
|
||||
const onChange = () => setMatches(mql.matches);
|
||||
onChange();
|
||||
mql.addEventListener('change', onChange);
|
||||
return () => mql.removeEventListener('change', onChange);
|
||||
}, [query]);
|
||||
|
||||
return matches;
|
||||
}
|
||||
|
||||
/** 与 Tailwind `md` 断点一致:< 768px 视为移动端 */
|
||||
export function useIsMobile(): boolean {
|
||||
return useMediaQuery('(max-width: 767px)');
|
||||
}
|
||||
Reference in New Issue
Block a user