This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

Hello everyone, I’m Dudu, some common Dom operations, through a simple Hook can be obtained, you know? (These DOM operations are quite common, I believe it will be able to help you, recommend collection oh ~)

Learning from ahooks requires that you learn with the attitude that you may not, but you can’t help but know, in case you do

This article introduces: useEventListener, useHover, useFullscreen, useMouse, useScroll, useResponsive, useTextSelection, useSize, 8 apis

As before we marked the importance of the hook by ⭐️

⭐️ : General; ⭐️⭐️ : important; ⭐️⭐️ port: Very important

The special hook useReactive can help you a lot. When the special hooks are special, the special hook useReactive can help you a lot.

Example: Domesy/ahook

AddEventListener useEventListener management

Recommended index: ⭐️⭐️ port ️

UseEventListener: Listens for events, functions, and can be received as Dom nodes or ref objects

Code examples:

import React, { useRef, useState } from 'react'; import { Button } from 'antd'; import { useEventListener } from 'ahooks'; const Mock: React.FC<any> = () => { const [value, setValue] = useState(0); const [value1, setValue1] = useState(''); const clickHandler = () => { setValue(value + 1); }; const ref = useRef<any>(null); useEventListener('click', clickHandler, { target: ref }); const keyDownHandler = (ev: KeyboardEvent) => { setValue1(ev.code); }; useEventListener('keydown', keyDownHandler); return ( <> <div style={{fontWeight: 'bolder', marginBottom: </div> <Button type='primary' ref={ref}> </div style={{fontWeight: 8 px 'bolder, margin:' 0 '}} > monitor keyboard effect: < / div > < p > please input keyboard events: {value1} < / p > < / a >). }; export default Mock;Copy the code

UseHover Mouse hover

Recommended index: ⭐️⭐️

UseHover: A Hook to track whether a DOM element has a mouse hover. And can be received as a Dom node or ref object

Code sample

import React, { useRef, useState } from 'react';
  import { Button } from 'antd';
  import { useHover } from 'ahooks';

  const Mock: React.FC<any> = () = > {

    const ref = useRef<any> (null);
    const isHovering = useHover(ref);

    const isHovering1 = useHover(() = > document.getElementById('hover-div'), {
      onEnter: () = > {
        message.info('Triggered on entry');
      },
      onLeave: () = > {
        message.info('Triggered when leaving'); }});return (
      <div>
        <div ref={ref} style={{fontWeight: 'bolder', marginBottom: 8}} >Obtain from ref:</div>
        <div ref={ref}>Hover the mouse over: {isHovering? 'stay' : 'leave '}</div>
        <div style={{fontWeight: 'bolder', margin:'8px 0'}} >Image DOM element acquisition:</div>
        <div id="hover-div">Mouse over: {isHovering1? 'stay' : 'leave '}</div>
      </div>
    );
  };

  export default Mock;
Copy the code

UseFullscreen dom full screen

Recommended index: ⭐️⭐️

UseFullscreen: includes isFullscreen, setFull, exitFull, and toggleFull. UseFullscreen can be a DOM node or ref

Code examples:

  import React, { useRef, useState } from 'react';
  import { Button } from 'antd';
  import { useFullscreen } from 'ahooks';

  const Mock: React.FC<any> = () = > {
    const ref = useRef<any> (null);
    const [isFullscreen, { enterFullscreen, exitFullscreen, toggleFullscreen }] = useFullscreen(ref);
    const [, { enterFullscreen: enterFullscreenImg }] = useFullscreen(() = > document.getElementById('fullscreen-img'));

    return (
      <div>
        <div ref={ref} style={{ background: 'white' }}>
          <div style={{fontWeight: 'bolder', marginBottom: 8}} >Basic usage:</div>
          <div>Current status: {isFullscreen? 'Full screen' : 'Not full screen '}</div>
          <div style={{marginTop: 8.display: 'flex', justifyContent: 'flex-start'}} >
            <Button type='primary' style={{marginRight: 8}} onClick={enterFullscreen}>Full screen</Button>
            <Button type='primary' style={{marginRight: 8}} onClick={exitFullscreen}>Exit full screen</Button>
            <Button type='primary' onClick={toggleFullscreen}>Switch state</Button>
          </div>
        </div>
        <div style={{fontWeight: 'bolder', margin:'8px 0'}} >Full screen:</div>
        <img id="fullscreen-img" src={'https://ahooks.js.org/static/react-hooks.dd0f9d30.jpg'} style={{ width: 320 }} alt="" />
        <div style={{marginTop: 8.display: 'flex', justifyContent: 'flex-start'}} >
          <Button type='primary' style={{marginRight: 8}} onClick={enterFullscreenImg}>Full screen</Button>
        </div>
      </div>
    );
  };

  export default Mock;
Copy the code

UseMouse mouse position

Recommended index: ⭐️⭐️ port ️

UseMouse: Get the mouse’s viewable height, relative width, and distance from the screen

Code examples:

import React from 'react';
  import { Button } from 'antd';
  import { useMouse } from 'ahooks';

  const Mock: React.FC<any> = () = > {

    const mouse = useMouse();

    return (
      <>
        <div>Horizontal coordinates relative to the screen (screenX) : {mouse.screenx}</div>
        <div>Vertical coordinates relative to the screen (screenY) : {mouse.screeny}</div>
        <div>Horizontal coordinates relative to the inside of the browser (clientX) : {mouse.clientx}</div>
        <div>Vertical coordinates relative to the inside of the browser (clientY) : {mouse.clienty}</div>
        <div>Horizontal coordinates of the entire browser relative to the browser (pageX) : {mouse.pagex}</div>
        <div>The vertical coordinate of the entire browser relative to the browser (pageY) : {mouse.pagey}</div>
      </>
    );
  };

  export default Mock;
              
Copy the code

UseScroll gets the element scroll position

Recommended index: ⭐️⭐️

UseScroll: Gets the scrolling state of the element, receives a DOM node or Ref object

Const scroll = useScroll(ref) const scroll = useScroll(ref)

Code sample

import React, { useRef } from 'react';
  import { Button } from 'antd';
  import { useScroll } from 'ahooks';

  const Mock: React.FC<any> = () = > {

    const ref = useRef<any> (null);
    const scroll = useScroll(ref);

    return (
      <>
        <div>Scroll Left: {scroll? . Left | | 0} scroll Top: {scroll? .top || 0}</div>
        <div ref={ref} style={{height: 200.width: 200.border: '1px solid #eee', overflow: 'scroll',  whiteSpace: 'nowrap', fontSize: 32}} >
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
          <div>If it helps you, please click Star to support it! ~ ~</div>
        </div>
      </>
    );
  };

  export default Mock;
Copy the code

UseResponsive Obtains responsive information

Recommended index: ⭐️⭐️ port ️

UseResponsive: You can obtain and subscribe to responsive information of a browser window

  • The default configuration is the same as bootstrap: {xs: 0, sm: 576, MD: 768, LG: 992, xl: 1200}
  • If you want to configure responsive breakpoints yourself, you need to use configResponsive, and the value should be configured once, not multiple times

Code examples:

import React from 'react';
  import { Button } from 'antd';
  import { configResponsive, useResponsive } from 'ahooks';

  configResponsive({
    small: 0.middle: 800.large: 1200});const Mock: React.FC<any> = () = > {

    const responsive = useResponsive();

    return (
      <>
        <div>Please change the size of the page</div>
        {
          Object.keys(responsive).map((key) => (
            <p key={key}>
              {key} {responsive[key] ? '✔' : '✘'}
            </p>))}</>
    );
  };

  export default Mock;
Copy the code

UseTextSelection Listens for the selected location and content

Recommended index: ⭐️⭐️ port ️

UseTextSelection: Can be retrieved globally or by specification (DOM or Ref)

There are: select text value, height width, coordinate function, can also be combined with Popover to make the translation function, very easy to use ~~

Code sample

import React, { useRef, useEffect } from 'react';
  import { Popover, Spin } from 'antd';
  import { useTextSelection, useRequest } from 'ahooks';

  const getResult = (keyword: string) :Promise<string> = > {consttrimedText = keyword.trim() ! = =' ';
    if(! trimedText) {return Promise.resolve(' ');
    }
    return new Promise((resolve) = > {
      setTimeout(() = > resolve("Can make some translation effect, select text:" + keyword), 1000);
    });
  };

  const Test: React.FC<any> = () = > {

    const { text = ' ', left = 0, top = 0, height = 0, width = 0 } = useTextSelection(() = >
      document.querySelector('#translate-dom'));const [visible, setVisible] = useState(false);

    const { data, run, loading } = useRequest(getResult, {
      manual: true}); useEffect(() = > {
      if (text.trim() === ' ') {
        setVisible(false);
        return;
      }
      setVisible(true);
      run(text);
    }, [text]);

    return <>
      <div id='translate-dom' style={{ padding: 20.border: '1px solid #eee', marginTop: 8}} >Slide copy to see the effect, please click Star to support it</div>
      <Popover
        content={<Spin spinning={loading}>{loading ? 'Translating... ' : data}</Spin>}
        visible={visible}
      >
        <span
          style={{
            position: 'fixed',
            top: "top"+px.left: "left"+px.height: "height"+px.width: "width"+px.pointerEvents: 'none'}} / >
      </Popover>
    </>
  }
  const Mock: React.FC<any> = () = > {

    const ref = useRef<any> ();const size = useSize(ref);

    const dom = document.querySelector('body');
    const size1 = useSize(dom);

    return (
      <>
        <div style={{ fontWeight: 'bold', marginBottom: 8}} >Obtain from ref:</div>
        <div ref={ref}>Change the screen size (div) : width: {sie.width} px, height: {sie.height} px</div>
        <div style={{ fontWeight: 'bold', margin: '8px 0'}} >Get from DOM:</div>
        <div ref={ref}>Change screen size (body) : width: {size1.width} px, height: {size1.height} px</div>
      </>
    );
  };

  export default Mock;
Copy the code

UseSize listens for screen sizes

Recommended index: ⭐️⭐️

UseSize: Monitors the size of the DOM, either a DOM node or a REF

Code examples:

import React, { useRef } from 'react';
  import { Button } from 'antd';
  import { useSize } from 'ahooks';

  const Mock: React.FC<any> = () = > {

    const ref = useRef<any> ();const size = useSize(ref);

    const dom = document.querySelector('body');
    const size1 = useSize(dom);

    return (
      <>
        <div style={{ fontWeight: 'bold', marginBottom: 8}} >Obtain from ref:</div>
        <div ref={ref}>Change screen size (div) : width: {size? .width} px, height: {size? .height} px</div>
        <div style={{ fontWeight: 'bold', margin: '8px 0'}} >Get from DOM:</div>
        <div ref={ref}>Change the screen size (body) : width: {size1? .width} px, height: {size1? .height} px</div>
      </>
    );
  };

  export default Mock;
Copy the code

End

Other articles:

  • Build the React mobile framework out of the box
  • Build your Own Ant Design Pro V5
  • More than 10,000 words summarize all the new features of ES6-ES12