前言
2019 年写的分析,慎重观看。不过其中的思路还是值得学习的。
useBattery
- 作用:获取电池信息
- 原理 navigator.getBattery, 并监听chargingchange, levelchange,chargingtimechange,dischargingtimechange事件。
useGeolocation
- 获取地址位置
- Geolocation, navigator.geolocation.getCurrentPosition获取地址位置, navigator.geolocation.watchPosition监听变化。
useLocation
- 作用:获取浏览器location信息
- 原理: 监听window的popstate,pushstate,replacestate事件。
useEffect(() => {
const onPopstate = () => setState(buildState('popstate'));
const onPushstate = () => setState(buildState('pushstate'));
const onReplacestate = () => setState(buildState('replacestate'));
on(window, 'popstate', onPopstate);
on(window, 'pushstate', onPushstate);
on(window, 'replacestate', onReplacestate);
return () => {
off(window, 'popstate', onPopstate);
off(window, 'pushstate', onPushstate);
off(window, 'replacestate', onReplacestate);
};
}, []);
useMedia
使用window.matchMedia获得MediaQueryList 对象,然后添加监听事件。
import { useEffect, useState } from 'react';
import { isClient } from '