介绍

主要介绍:useEventListener(管理 addEventListener)、useHover(鼠标悬停状态)、useFullscreen(全屏功能)、useMouse(获取鼠标位置)、useScroll(获取元素滚动的位置)、useResponsive(响应式信息)、useTextSelection(监听选取的位置及内容)、useSize(监听屏幕尺寸)

具体的项目展示:Domesy/Dom

管理 addEventLinstener

  • useEventListener:监听事件
  • useEventListener(事件, 监听的函数, {target: ref (DOM节点或者是ref对象)});

    代码演示

    image.png

    详细代码

    ```typescript import React, { useRef, useState } from ‘react’; import { Button } from ‘antd’; import { useEventListener } from ‘ahooks’;

    const Mock: React.FC = () => { const [value, setValue] = useState(0); const [value1, setValue1] = useState(‘’);

    const clickHandler = () => {

    1. setValue(value + 1);

    };

    const ref = useRef(null); useEventListener(‘click’, clickHandler, { target: ref }); const keyDownHandler = (ev: KeyboardEvent) => {

    1. setValue1(ev.code);

    };

    useEventListener(‘keydown’, keyDownHandler); return (

    1. <>
    2. <div style={{fontWeight: 'bolder', marginBottom: 8}}>基础用法:</div>
    3. <Button type='primary' ref={ref}>
    4. 点击次数 { value } 次
    5. </Button>
    6. <div style={{fontWeight: 'bolder', margin:'8px 0'}}>监听键盘效果:</div>
    7. <p>请输入键盘的事件:{value1}</p>
    8. </>

    ); };

    export default Mock;

  1. <a name="n8pYX"></a>
  2. ## 鼠标悬停
  3. - **useHover:一个用于追踪 dom 元素是否有鼠标悬停的 Hook。**
  4. - **可传入DOM节点或者Ref,并且可以有进入的方法和离开的方式**
  5. <a name="Oj1iU"></a>
  6. ### 代码演示
  7. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/310196/1636105986904-e9180b75-16c6-4583-9555-5b741d1d091d.png#clientId=u9166ccc8-d2a2-4&from=paste&height=258&id=ud5a6ef2c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=258&originWidth=766&originalType=binary&ratio=1&size=22582&status=done&style=none&taskId=uebe607c0-439b-491e-9d2c-120f39303ec&width=766)
  8. <a name="bbqEc"></a>
  9. ### 详细代码
  10. ```typescript
  11. import React, { useRef, useState } from 'react';
  12. import { Button } from 'antd';
  13. import { useHover } from 'ahooks';
  14. const Mock: React.FC<any> = () => {
  15. const ref = useRef<any>(null);
  16. const isHovering = useHover(ref);
  17. const isHovering1 = useHover(() => document.getElementById('hover-div'), {
  18. onEnter: () => {
  19. message.info('进入的时候触发');
  20. },
  21. onLeave: () => {
  22. message.info('离开的时候触发');
  23. },
  24. });
  25. return (
  26. <div>
  27. <div ref={ref} style={{fontWeight: 'bolder', marginBottom: 8}}>通过ref获取:</div>
  28. <div ref={ref}>鼠标放入上边:{isHovering ? '停留' : '离开'} </div>
  29. <div style={{fontWeight: 'bolder', margin:'8px 0'}}>图片DOM 元素获取:</div>
  30. <div id="hover-div">鼠标放入上边:{isHovering1 ? '停留' : '离开'}</div>
  31. </div>
  32. );
  33. };
  34. export default Mock;

DOM全屏

  • useFullscreen:主要包含 isFullscreen(是否全屏)、setFull(设置全屏)、exitFull(退出全屏)、toggleFull(切换全屏)的操作
  • 使用:const [isFullscreen, { setFull, exitFull, toggleFull }] = useFullScreen(target, options?:Options);
  • 可以是DOM节点,或者是ref

代码演示

image.png

详细代码

  1. import React, { useRef, useState } from 'react';
  2. import { Button } from 'antd';
  3. import { useFullscreen } from 'ahooks';
  4. const Mock: React.FC<any> = () => {
  5. const ref = useRef<any>(null);
  6. const [isFullscreen, { setFull, exitFull, toggleFull }] = useFullscreen(ref);
  7. const [, { setFull: setFullImg, exitFull: exitFullImg, toggleFull: toggleFullImg }] = useFullscreen(() => document.getElementById('fullscreen-img'));
  8. return (
  9. <div>
  10. <div ref={ref} style={{ background: 'white' }}>
  11. <div style={{fontWeight: 'bolder', marginBottom: 8}}>基础用法:</div>
  12. <div>当前状态:{isFullscreen ? '全屏状态' : '非全屏状态'} </div>
  13. <div style={{marginTop: 8, display: 'flex', justifyContent: 'flex-start'}}>
  14. <Button type='primary' style={{marginRight: 8}} onClick={setFull}>全屏</Button>
  15. <Button type='primary' style={{marginRight: 8}} onClick={exitFull}>退出全屏</Button>
  16. <Button type='primary' onClick={toggleFull}>切换状态</Button>
  17. </div>
  18. </div>
  19. <div style={{fontWeight: 'bolder', margin:'8px 0'}}>图片全屏:</div>
  20. <img id="fullscreen-img" src={'https://ahooks.js.org/static/react-hooks.dd0f9d30.jpg'} style={{ width: 320 }} alt="" />
  21. <div style={{marginTop: 8, display: 'flex', justifyContent: 'flex-start'}}>
  22. <Button type='primary' style={{marginRight: 8}} onClick={setFullImg}>全屏</Button>
  23. </div>
  24. </div>
  25. );
  26. };
  27. export default Mock;

鼠标位置

  • useMouse:可获取鼠标的可视区宽高、相对宽高、和距离屏幕的宽高

    代码演示

    image.png

    详细代码

    1. import React from 'react';
    2. import { Button } from 'antd';
    3. import { useMouse } from 'ahooks';
    4. const Mock: React.FC<any> = () => {
    5. const mouse = useMouse();
    6. return (
    7. <>
    8. <div>相对于屏幕的水平坐标(screenX):{mouse.screenX}</div>
    9. <div>相对于屏幕的垂直坐标(screenY):{mouse.screenY}</div>
    10. <div>相对于浏览器内部的水平坐标(clientX):{mouse.clientX}</div>
    11. <div>相对于浏览器内部的垂直坐标(clientY):{mouse.clientY}</div>
    12. <div>相对于浏览器整个浏览器的水平坐标(pageX):{mouse.pageX}</div>
    13. <div>相对于浏览器整个浏览器的垂直坐标(pageY):{mouse.pageY}</div>
    14. </>
    15. );
    16. };
    17. export default Mock;

    获取元素滚动位置

  • useScroll:获取元素的滚动状态

  • 使用:const scroll = useScroll(ref) 接收一个DOM节点或者Ref对象

    代码演示

    image.png

    详细代码

    1. import React, { useRef } from 'react';
    2. import { Button } from 'antd';
    3. import { useScroll } from 'ahooks';
    4. const Mock: React.FC<any> = () => {
    5. const ref = useRef<any>(null);
    6. const scroll = useScroll(ref);
    7. return (
    8. <>
    9. <div>滚动Left:{scroll.left} 滚动Top: {scroll.top}</div>
    10. <div ref={ref} style={{height: 200, width: 200, border: '1px solid #eee', overflow: 'scroll', whiteSpace: 'nowrap', fontSize: 32}}>
    11. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    12. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    13. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    14. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    15. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    16. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    17. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    18. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    19. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    20. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    21. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    22. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    23. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    24. <div>如果对你有帮助,请点个Star支持下吧!~~</div>
    25. </div>
    26. </>
    27. );
    28. };
    29. export default Mock;

    响应式信息

  • useResponsive:可以获取并订阅浏览器窗口的响应式信息

  • 默认的配置是与 bootstrap 一致:{ xs: 0, sm: 576, md: 768, lg: 992, xl: 1200}
  • 如果想要自己配置响应式的断点,需要使用 configResponsive, 并且值需要配置一次,不要多次使用

    代码演示

    image.png

    详细代码

    1. import React from 'react';
    2. import { Button } from 'antd';
    3. import { configResponsive, useResponsive } from 'ahooks';
    4. configResponsive({
    5. small: 0,
    6. middle: 800,
    7. large: 1200,
    8. });
    9. const Mock: React.FC<any> = () => {
    10. const responsive = useResponsive();
    11. return (
    12. <>
    13. <div>请改变页面的尺寸</div>
    14. {
    15. Object.keys(responsive).map((key) => (
    16. <p key={key}>
    17. {key} {responsive[key] ? '✔' : '✘'}
    18. </p>
    19. ))
    20. }
    21. </>
    22. );
    23. };
    24. export default Mock;

    监听选取位置及内容

  • useTextSelection: 可以全局获取,也可以制定获取(DOM或Ref)

  • 有:选取文本的值,高度宽度、坐标的功能,也可以配合Popover作出翻译的功能,非常好用~~

    代码演示

    image.png

    详细代码

    1. import React, { useRef, useEffect } from 'react';
    2. import { Popover, Spin } from 'antd';
    3. import { useTextSelection, useRequest } from 'ahooks';
    4. const getResult = (keyword: string): Promise<string> => {
    5. const trimedText = keyword.trim() !== '';
    6. if (!trimedText) {
    7. return Promise.resolve('');
    8. }
    9. return new Promise((resolve) => {
    10. setTimeout(() => resolve("可以作出一些翻译效果,选取的文字:" + keyword), 1000);
    11. });
    12. };
    13. const Test: React.FC<any> = () => {
    14. const { text = '', left = 0, top = 0, height = 0, width = 0 } = useTextSelection(() =>
    15. document.querySelector('#translate-dom'),
    16. );
    17. const [visible, setVisible] = useState(false);
    18. const { data, run, loading } = useRequest(getResult, {
    19. manual: true,
    20. });
    21. useEffect(() => {
    22. if (text.trim() === '') {
    23. setVisible(false);
    24. return;
    25. }
    26. setVisible(true);
    27. run(text);
    28. }, [text]);
    29. return <>
    30. <div id='translate-dom' style={{ padding: 20, border: '1px solid #eee', marginTop: 8}}>
    31. 滑动复制下,看看效果,请点个 Star 支持一下吧~
    32. </div>
    33. <Popover
    34. content={<Spin spinning={loading}>{loading ? 'Translating……' : data}</Spin>}
    35. visible={visible}
    36. >
    37. <span
    38. style={{
    39. position: 'fixed',
    40. top: "top" + px,
    41. left: "left" + px,
    42. height: "height" + px,
    43. width: "width" + px,
    44. pointerEvents: 'none',
    45. }}
    46. />
    47. </Popover>
    48. </>
    49. }
    50. const Mock: React.FC<any> = () => {
    51. const ref = useRef<any>();
    52. const size = useSize(ref);
    53. const dom = document.querySelector('body');
    54. const size1 = useSize(dom);
    55. return (
    56. <>
    57. <div style={{ fontWeight: 'bold', marginBottom: 8}}>通过ref获取:</div>
    58. <div ref={ref}>改变屏幕尺寸(div): 宽度:{size.width} px, 高度:{size.height} px</div>
    59. <div style={{ fontWeight: 'bold', margin: '8px 0'}}>通过dom获取:</div>
    60. <div ref={ref}>改变屏幕尺寸(body): 宽度:{size1.width} px, 高度:{size1.height} px</div>
    61. </>
    62. );
    63. };
    64. export default Mock;

    监听屏幕尺寸

  • useSize: 可监听dom的尺寸变化

  • 可以是DOM节点,或者是ref

    代码演示

    image.png

    详细代码

    1. import React, { useRef } from 'react';
    2. import { Button } from 'antd';
    3. import { useSize } from 'ahooks';
    4. const Mock: React.FC<any> = () => {
    5. const ref = useRef<any>();
    6. const size = useSize(ref);
    7. const dom = document.querySelector('body');
    8. const size1 = useSize(dom);
    9. return (
    10. <>
    11. <div style={{ fontWeight: 'bold', marginBottom: 8}}>通过ref获取:</div>
    12. <div ref={ref}>改变屏幕尺寸(div): 宽度:{size.width} px, 高度:{size.height} px</div>
    13. <div style={{ fontWeight: 'bold', margin: '8px 0'}}>通过dom获取:</div>
    14. <div ref={ref}>改变屏幕尺寸(body): 宽度:{size1.width} px, 高度:{size1.height} px</div>
    15. </>
    16. );
    17. };
    18. export default Mock;