当前位置: 首页 > news >正文

React封装倒计时按钮

背景

在开发过程中,经常需要使用到倒计时的场景,当用户点击后,按钮进行倒计时,然后等待邮件或者短信发送,每次都写重复代码,会让代码显得臃肿,所以封装一个组件来减少耦合

创建一个倒计时组件

在这里插入图片描述

编辑基本框架

设计3个参数,一个是倒计时时长,一个是开始时执行的方法,一个是展示文本

import React, { useState, useEffect, useRef } from 'react';
import { Button } from 'antd';// 定义 CountdownButton 的属性接口
interface CountdownButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> {countdownTime?: number;text?: string;onStart?: () => void;
}const CountdownButton: React.FC<CountdownButtonProps> = ({ countdownTime = 60, text = '获取验证码', onStart, ...restProps }) => {const [isDisabled, setIsDisabled] = useState(false);const [buttonText, setButtonText] = useState(text);// 使用useRef来保存倒计时的当前值,避免状态重置const countdownRef = useRef(countdownTime);const intervalRef = useRef<number | null>(null);return (<Button >{buttonText}</Button>);
};export default CountdownButton;

实现倒计时方法

实现剩余时间修改方法

    // 使用自定义的setCountdownRef函数来更新倒计时值const setCountdownRef = (update: (current: number) => number) => {const newCountdown = update(countdownRef.current);countdownRef.current = newCountdown;};

实现开启倒计时方法

   const handleStartCountdown = () => {// 立即更新按钮文本和状态setButtonText(`${countdownRef.current}s后重试`);setIsDisabled(true);if (typeof onStart === 'function') {onStart();}// 如果已经有定时器存在,则清除它if (intervalRef.current !== null) {clearInterval(intervalRef.current!);}intervalRef.current = setInterval(() => {setButtonText(`${countdownRef.current}s后重试`);setCountdownRef((prevCountdown) => {if (prevCountdown <= 1) {clearInterval(intervalRef.current!);intervalRef.current = null;setButtonText(text);setIsDisabled(false);return countdownTime; // 重置倒计时时间}return prevCountdown - 1;});}, 1000);

实现清楚定时器方法

    // 清除定时器useEffect(() => {return () => {if (intervalRef.current !== null) {clearInterval(intervalRef.current!);}};}, []);

完整代码

import React, { useState, useEffect, useRef } from 'react';
import { Button } from 'antd';// 定义 CountdownButton 的属性接口
interface CountdownButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'onClick'> {countdownTime?: number;text?: string;onStart?: () => void;
}const CountdownButton: React.FC<CountdownButtonProps> = ({ countdownTime = 60, text = '获取验证码', onStart, ...restProps }) => {const [isDisabled, setIsDisabled] = useState(false);const [buttonText, setButtonText] = useState(text);// 使用useRef来保存倒计时的当前值,避免状态重置const countdownRef = useRef(countdownTime);const intervalRef = useRef<number | null>(null);// 清除定时器useEffect(() => {return () => {if (intervalRef.current !== null) {clearInterval(intervalRef.current!);}};}, []);const handleStartCountdown = () => {// 立即更新按钮文本和状态setButtonText(`${countdownRef.current}s后重试`);setIsDisabled(true);if (typeof onStart === 'function') {onStart();}// 如果已经有定时器存在,则清除它if (intervalRef.current !== null) {clearInterval(intervalRef.current!);}intervalRef.current = setInterval(() => {setButtonText(`${countdownRef.current}s后重试`);setCountdownRef((prevCountdown) => {if (prevCountdown <= 1) {clearInterval(intervalRef.current!);intervalRef.current = null;setButtonText(text);setIsDisabled(false);return countdownTime; // 重置倒计时时间}return prevCountdown - 1;});}, 1000);// 立即减少一次倒计时,使首次显示正确的剩余时间setCountdownRef((prevCountdown) => prevCountdown - 1);};// 使用自定义的setCountdownRef函数来更新倒计时值const setCountdownRef = (update: (current: number) => number) => {const newCountdown = update(countdownRef.current);countdownRef.current = newCountdown;};return (<Button {...restProps} onClick={handleStartCountdown} disabled={isDisabled}>{buttonText}</Button>);
};export default CountdownButton;

使用方法

<CountdownButton countdownTime={60} text={"获取验证码"} onStart={sendMsg} type="primary" />

效果

在这里插入图片描述

http://www.lryc.cn/news/521935.html

相关文章:

  • 深入探究Linux树状目录结构
  • Realsense相机驱动安装及其ROS通讯配置——机器人抓取系统基础系列(四)
  • linux安装nvm
  • 图论1-问题 C: 算法7-6:图的遍历——广度优先搜索
  • 基于 STM32 的多功能时间管理器项目
  • Java工程结构:二方库依赖规约
  • Django自带admin管理系统使用
  • Jmeter 简单使用、生成测试报告(一)
  • 手摸手实战前端项目CI CD
  • 【Elasticsearch】搜索类型介绍,以及使用SpringBoot实现,并展现给前端
  • K8S中的Pod调度之亲和性调度
  • 高等数学学习笔记 ☞ 不定积分的积分法
  • 【HTTP】详解
  • cursor重构谷粒商城01——为何要重构谷粒商城
  • 如何在 ASP.NET Core 中实现速率限制?
  • STM32-笔记43-低功耗
  • Facebook 隐私风波:互联网时代数据安全警钟
  • Java 中的 ZoneOffset
  • amis模板语法、数据映射与表达式
  • 频域增强通道注意力机制EFCAM模型详解及代码复现
  • GitLab 国际站中国大陆等地区停服,如何将数据快速迁移到云效
  • BPG图像库和实用程序(译)
  • 简述1个业务过程:从客户端调用接口,再到调用中间件(nacos、redis、kafka、feign),数据库的过程
  • 01.02、判定是否互为字符重排
  • 什么是.NET中的反射,它有哪些应用场景
  • Linux离线部署ELK
  • 解决 chls.pro/ssl 无法进入问题
  • Rust 游戏开发框架指南
  • hadoop3.3和hive4.0安装——单节点
  • centos安装golang