React Hooks --- 分享自己开发中常用的自定义的Hooks (1)

为什么要使用自定义 Hooks

自定义 Hooks 是 React 中一种复用逻辑的机制,通过它们可以抽离组件中的逻辑,使代码更加简洁、易读、易维护。它们可以在多个组件中复用相同的逻辑,减少重复代码。

1、useThrottle

代码
import React,{ useRef, useState,useEffect } from "react";/*** useThrottle:一个节流的 hook,用于限制状态更新的频率。** @param {any} initialState 初始状态* @param {number} delay 节流间隔时间,默认为 500 毫秒* @returns {any} 节流后的状态*/
export const useThrottle = (initialState, delay = 5000) => {const [state, setState] = useState(initialState);const timeout = useRef();const nextValue = useRef(null);const hasNextValue = useRef(false);useEffect(() => {if (timeout.current) {nextValue.current = initialState;hasNextValue.current = true;} else {setState(initialState);const timeoutCallback = () => {if (hasNextValue.current) {setState(nextValue.current);hasNextValue.current = false;}timeout.current = undefined;};timeout.current = setTimeout(timeoutCallback, delay);}return () => {timeout.current && clearTimeout(timeout.current);}}, [initialState]);return state;
};
用法
import { useThrottle } from './useThrottle';const value = useThrottle(state, 500);

2、useVirtual

代码
import { useEffect, useState } from 'react';/*** useVirtual:一个虚拟滚动的 hook,用于优化长列表的渲染性能。** @param {object} listRef 列表的引用对象* @param {Array} list 初始列表数据* @param {boolean} isFullScreen 是否全屏显示* @returns {Array} 显示在视图中的列表数据和 padding 样式*/
export const useVirtual = (listRef, list, isFullScreen) => {const origin = list;let viewHeight = null;let itemHeight = 0;let dur = 0;const rootFontSize = parseInt(document.documentElement.style.fontSize);const [viewList, setViewList] = useState(list);const [startIndex, setStartIndex] = useState(0);const [endIndex, setEndIndex] = useState(0);const [padding, setPadding] = useState({paddingTop: 0,paddingBottom: 0,});useEffect(() => {init(listRef);}, []);useEffect(() => {initData(listRef.current);update();}, [startIndex]);function init(ref) {initData(ref.current);render(startIndex, dur + 1);eventBind(ref.current);}function initData(dom) {const target = isFullScreen ? document.documentElement : dom;viewHeight = isFullScreen ? target.offsetHeight : target.parentNode.offsetHeight;itemHeight = target.getElementsByClassName('virtual-item')[0].offsetHeight;dur = Math.floor(viewHeight / itemHeight);}function eventBind(dom) {const eventTarget = isFullScreen ? window : dom.parentNode;eventTarget.addEventListener('scroll', handleScroll, false);}function render(startIndex, endIndex) {setViewList(() => origin.slice(startIndex, endIndex));setEndIndex(() => startIndex + dur + 1);}function handleScroll(e) {e.stopPropagation();const target = isFullScreen ? document.documentElement : listRef.current.parentNode;setStartIndex(() => Math.floor(target.scrollTop / itemHeight));}function update() {if (startIndex === endIndex) return;setEndIndex(() => startIndex + dur);render(startIndex, endIndex);setPadding(() => {return {paddingTop: (startIndex * itemHeight) / rootFontSize,paddingBottom: ((origin.length - endIndex) * itemHeight) / rootFontSize,};});}return [viewList, padding];
};
用法
import { useRef } from 'react';
import { useVirtual } from './useVirtual';const listRef = useRef();
const [viewList, padding] = useVirtual(listRef, initialList, false);

3、useCopyToClipboard

代码
import { message } from 'antd';/*** useCopyToClipboard:一个 hook,用于复制文本到剪贴板。** @returns {Array} 包含单个函数 `handleCopy`,用于复制文本到剪贴板*/
const useCopyToClipboard = () => {function handleCopy(text) {if (text) {let input = document.createElement('input');input.type = 'text';input.value = text;input.style.position = 'fixed';input.style.opacity = '0';document.body.appendChild(input);input.select();if (document.execCommand('copy')) {message.success('复制成功');} else {message.error('复制失败');}document.body.removeChild(input);} else {message.error('复制失败');}}return [handleCopy];
};export default useCopyToClipboard;
用法
import useCopyToClipboard from './useCopyToClipboard';const [handleCopy] = useCopyToClipboard();const copyText = () => {handleCopy('需要复制的文本');
};

4、useSmoothEnter

代码
import { useState, useEffect, useRef } from 'react';/*** useSmoothEnter:一个 hook,在 DOM 元素进入视口时添加平滑的进入动画。** @returns {object} ref - 一个可以附加到 DOM 元素的 ref 对象,用于动画效果*/
const useSmoothEnter = () => {const ref = useRef(null);const [isVisible, setIsVisible] = useState(false);const [animationStyle, setAnimationStyle] = useState({animation: '',animationPlayState: 'paused',});useEffect(() => {const observer = new IntersectionObserver((entries) => {const [entry] = entries;setIsVisible(entry.isIntersecting);});const element = ref.current;if (element) {observer.observe(element);return () => {observer.unobserve(element);};}}, [ref]);useEffect(() => {if (isVisible) {setAnimationStyle({animation: 'enterAnimation 1s ease',animationPlayState: 'running',});}}, [isVisible]);useEffect(() => {const element = ref.current;if (element) {element.style.animation = animationStyle.animation;element.style.animationPlayState = animationStyle.animationPlayState;}}, [animationStyle]);return ref;
};export default useSmoothEnter;
用法
import useSmoothEnter from './useSmoothEnter';const ref = useSmoothEnter();return <div ref={ref} className="animated-element">内容</div>;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/41539.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

三叶青图像识别研究简概

三叶青图像识别研究总概 文章目录 前言一、整体目录介绍二、前期安排三、构建图像分类数据集四、模型训练准备五、迁移学习模型六、在测试集上评估模型精度七、可解释性分析、显著性分析八、图像分类部署九、树莓派部署十、相关补充总结 前言 本系列文章为近期所做项目研究而作…

工作助手VB开发笔记(2)

今天继续讲功能 2.功能 2.9开机自启 设置程序随windows系统启动&#xff0c;其实就是就是将程序加载到注册表 Public Sub StartRunRegHKLM()REM HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Microsoft \ Windows \ CurrentVersion \ RunDim strName As String Applicat…

教师商调函流程详解

作为一名教师&#xff0c;您是否曾面临过工作调动的困惑&#xff1f;当您决定迈向新的教育环境&#xff0c;是否清楚整个商调函流程的每一个细节&#xff1f;今天&#xff0c;就让我们一起来探讨这一过程&#xff0c;确保您能够顺利地完成工作调动。 首先需要确定新调入的学校已…

裁员风波中的项目经理,如何自洽?

最近都在担心企业裁员&#xff0c;那么项目经理会不会也有被优化的风险呢&#xff1f; 答案是&#xff0c;一定会&#xff01; 今天从3个方面给大家阐述一下项目经理岗位的发展现状以及未来的趋势 01 项目经理被优化的可能性大吗&#xff1f; 02 哪一类项目经理会被最先裁员…

CSDN导入本地md文件图片不能正常回显问题

标题 搭建图像仓库获取图片URL 路径替换 因为服务器读取不到本地图片&#xff0c;故不能正常回显&#xff0c;因此想要正常回显图片&#xff0c;我们首先要做的就是搭建一个可以存放图片的服务器&#xff0c;像你可以选择购买一个云服务器、FastDFS图片服务器、Minio多云对象存…

信息收集-arping

信息收集-arping 简介 arping 是一个用于发送 ARP 请求和接收 ARP 回复的工具。它通常用于检查网络中的 IP 地址是否被使用&#xff0c;或发现网络中的重复 IP 地址。arping 工具类似于 ping 命令&#xff0c;但它使用的是 ARP 协议而不是 ICMP 协议。在 Kali Linux 中&#…

娱乐圈惊爆已婚男星刘端端深夜幽会

【娱乐圈惊爆&#xff01;已婚男星刘端端深夜幽会&#xff0c;竟是《庆余年》二皇子“戏外风云”】在这个信息爆炸的时代&#xff0c;娱乐圈的每一次风吹草动都能瞬间点燃公众的热情。今日&#xff0c;知名娱乐博主刘大锤的一则预告如同投入湖中的巨石&#xff0c;激起了层层涟…

纸电混合阶段,如何在线上实现纸电会档案的协同管理?

随着国家政策的出台和引导&#xff0c;电子会计档案的管理越来越规范&#xff0c;电子会计档案建设成为打通财务数字化最后一公里的重要一环。但是&#xff0c;当前很多企业的财务管理仍处于电子档案和纸质档案并行的阶段&#xff0c;如何能将其建立合理清晰关联&#xff0c;统…

《数字图像处理-OpenCV/Python》第17章:图像的特征描述

《数字图像处理-OpenCV/Python》第17章&#xff1a;图像的特征描述 本书京东 优惠购书链接 https://item.jd.com/14098452.html 本书CSDN 独家连载专栏 https://blog.csdn.net/youcans/category_12418787.html 第17章&#xff1a;图像的特征描述 特征检测与匹配是计算机视觉的…

javascript v8编译器的使用记录

我的机器是MacOS Mx系列。 一、v8源码下载构建 1.1 下载并更新depot_tools git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git export PATH/path/to/depot_tools:$PATH 失败的话可能是网络问题&#xff0c;可以试一下是否能ping通&#xff0c;连…

【代码随想录_Day25】452. 用最少数量的箭引爆气球 435. 无重叠区间 763. 划分字母区间

Day25 OK&#xff0c;今日份的打卡&#xff01;第二十五天 以下是今日份的总结用最少数量的箭引爆气球无重叠区间划分字母区间 以下是今日份的总结 用最少数量的箭引爆气球无重叠区间划分字母区间 今天的题目难度不低&#xff0c;而且非常的有意思&#xff0c;尽量还是写一些…

imx6ull/linux应用编程学习(11)CAN应用编程基础

关于裸机的can通信&#xff0c;会在其他文章发&#xff0c;这里主要讲讲linux上的can通信。 与I2C,SPI等同步通讯方式不同&#xff0c;CAN通讯是异步通讯&#xff0c;也就是没有时钟信号线来保持信号接收同步&#xff0c;也就是所说的半双工&#xff0c;无法同时发送与接收&…

python项目常见使用的传参调试方法

简介 你是否经常遇到下载的github开源知名项目&#xff0c;不知如何调试&#xff1f;只知道按说明的命令行运行&#xff1f;遇到异常或想改造也无从下手&#xff1f;这篇文档章将指导你如何入手调试别人的大型开源项目。 常见项目使用说明及代码如何调试 常见情况一 使用说…

16.【C语言】初识常见关键字 上

1.关键字由C语言自带&#xff0c;不能自创 2.关键字不作变量名 3.关键字举例&#xff1a; auto自动&#xff1a;每个局部变量都由auto修饰&#xff0c;含义&#xff1a;自动创建&#xff0c;自动销毁 auto int a0;等价于int a0; exturn:申明外部符号 register:寄存器关键字…

数据治理的制胜法宝:筛斗数据技术在现代企业管理中的应用

数据治理的制胜法宝&#xff1a;筛斗数据技术在现代企业管理中的应用 在当今这个数据驱动的时代&#xff0c;企业管理的效率和竞争力越来越依赖于对数据的精准把握和高效利用。然而&#xff0c;随着企业规模的扩大和业务复杂度的增加&#xff0c;数据治理成为了一个亟需解决的…

EasyExcel 单元格根据图片数量动态设置宽度

在使用 EasyExcel 导出 Excel 时&#xff0c;如果某个单元格是图片内容&#xff0c;且存在多张图片&#xff0c;此时就需要单元格根据图片数量动态设置宽度。 经过自己的研究和实验&#xff0c;导出效果如下&#xff1a; 具体代码如下&#xff1a; EasyExcel 版本 <depen…

Haxm安装失败的解决办法

确认你的处理器是否是Intel的&#xff0c;如果是AMD那就无法安装&#xff0c;如果是Intel的&#xff0c;再确认是否支持V1T 如果处理器是Intel的且支持VT&#xff0c;在开机时进入BIOS界面&#xff0c;不同的品牌进入BIOS的方法各不相同&#xff0c;通常是F2/F12/delete些&…

Python爬虫零基础实战,简洁实用!

1.爬虫简介 简单来讲&#xff0c;爬虫就是一个探测机器&#xff0c;它的基本操作就是模拟人的行为去各个网站溜达&#xff0c;点点按钮&#xff0c;查查数据&#xff0c;或者把看到的信息背回来。就像一只虫子在一幢楼里不知疲倦地爬来爬去。 你可以简单地想象&#xff1a;每个…

论文学习 --- RL Maximumdiffusion reinforcement learning

前言 个人拙见,如果我的理解有问题欢迎讨论 (●′ω`●) 文章出处:https://techxplore.com/news/2024-05-random-robots-reliable-ai-algorithm.html 研究背景 最大扩散强化学习(MaxDiff RL)是一种创新的强化学习方法,借鉴了统计力学中的扩散过程和最大熵原理。该方法在…

Hadoop的namenode启动不起来

1、 排查原因 Initialization failed for Block pool (Datanode Uuid a5d441af-d074-4758-a3ff-e1563b709267) service to node1/192.168.88.101:8020. Exiting. java.io.IOException: Incompatible clusterIDs in /data/dn: namenode clusterID CID-674c5515-3fe1-4a9c-881d…