react ahooks 表格中的每条数据都实现倒计时功能

在我们日常需求中, 实现一个倒计时是常见的需求, 或者一个页面有两个倒计时 我们都可以去实现, 但是如何实现在antd Table 中实现倒计时呢

现在有一个需求, 点击一条数据的下载操作, 开启30s倒计时, 点击另一个也是开启30s倒计时, 但是两者的倒计时互不冲突

在这里插入图片描述

可以使用 ahooks 中的 useCountDown

interval.js中的内容

import React , {useState}from 'react';
import { Typography, Button } from 'antd';
import { useCountDown } from 'ahooks';


const Interval = ({
  className,
  style,
  btnType = 'Link',
  disabled,
  onClick,
  children,
}) => {
  const [targetDate, setTargetDate] = useState();
  const [countdown] = useCountDown({
    targetDate,
  });

  const onDownload = event => {
    setTargetDate(Date.now() + 30000);
    onClick?.(event);
  };

  const Component = btnType === 'Link' ? Typography.Link : Button;

  return (
    <Component
      style={style}
      type={'primary'}
      className={className}
      onClick={onDownload}
      disabled={countdown !== 0 || disabled}>
      {countdown === 0
        ? children ? children : '下载'
        : `${Math.round(countdown / 1000)}s 后可重新点击导出`}
    </Component>
  );
};

export default Interval;

index.js

import React from 'react'
import { Table} from 'antd'
import Interval from './interval'

const InterValCom = () => {
  const dataSource = [
    {
      key: '1',
      name: '胡彦斌',
      age: 32,
      address: '西湖区湖底公园1号',
    },
    {
      key: '2',
      name: '胡彦祖',
      age: 42,
      address: '西湖区湖底公园1号',
    },
    {
      key: '3',
      name: '赵小刀',
      age: 36,
      address: '余杭区',
    },
  ];
  
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      dataIndex: 'option',
      key: 'option',
      render: (_) => <Interval onClick={() => console.log('下载ing.....')}
    />,
    },
  ];
  return <>

  <Table  
  columns={columns}
  dataSource={dataSource}
  />

  
  </>

}

export default InterValCom

猜你喜欢

转载自blog.csdn.net/zm_miner/article/details/126154541
今日推荐