最近在学习react hooks,而react-use是一个在开发中很常用的自定义钩子库,所以在这里做个学习总结。同时,楼主有在跟着学一个react项目,希望有机会和大家一起学习。点击跳转github项目地址
一、Sensor Hooks
Sensor Hooks监听某些接口中的更改,并强制组件以最新状态重新渲染。
- useMeasure:用来追踪元素尺寸
Demo:
import { useMeasure } from "react-use";
const Demo = () => {
const [ref, { x, y, width, height, top, right, bottom, left }] = useMeasure();
return (
<div ref={ref}>
<div>x: {x}</div>
<div>y: {y}</div>
<div>width: {width}</div>
<div>height: {height}</div>
<div>top: {top}</div>
<div>right: {right}</div>
<div>bottom: {bottom}</div>
<div>left: {left}</div>
</div>
);
};
- useKey:监听按键使用事件
Demo:
import {useKey} from 'react-use';
const Demo = () => {
const [count, set] = useState(0);
const increment = () => set(count => ++count);
useKey('ArrowUp', increment);
return (
<div>
Press arrow up: {count}
</div>
);
};
- useKeyPressEvent:用法与useKey相似,但useKeyPressEvent的钩子在按键监听中只会触发一次回调函数,而usekey则会触发多次,比如点击某个按键不松开,useKey的回调函数会一直执行,而useKeyPressEvent的回调函数只会执行一次
用法:
useKeyPressEvent('<key>', keydown);
useKeyPressEvent('<key>', keydown, keyup);
useKeyPressEvent('<key>', keydown, keyup, useKeyPress);
Demo:
import React, { useState } from React;
import {useKeyPressEvent} from 'react-use';
const Demo = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count => ++count);
const decrement = () => setCount(count => --count);
const reset = () => setCount(count => 0);
useKeyPressEvent(']', increment, increment);
useKeyPressEvent('[', decrement, decrement);
useKeyPressEvent('r', reset);
return (
<div>
<p>
Try pressing <code>[</code>, <code>]</code>, and <code>r</code> to
see the count incremented and decremented.</p>
<p>Count: {count}</p>
</div>
);
};
- useWindowSize:获取浏览器尺寸的钩子
Demo:
import {useWindowSize} from 'react-use';
const Demo = () => {
const {width, height} = useWindowSize();
return (
<div>
<div>width: {width}</div>
<div>height: {height}</div>
</div>
);
};
二、副作用钩子
- useSessionStorage:用于管理单个 sessionStorage 键 用法:
import {useSessionStorage} from 'react-use';
const Demo = () => {
const [value, setValue] = useSessionStorage('my-key', 'foo');
return (
<div>
<div>Value: {value}</div>
<button onClick={() => setValue('bar')}>bar</button>
<button onClick={() => setValue('baz')}>baz</button>
</div>
);
};