一个功能独立的操作倒计时按钮组件-react版本

2019-11-18  本文已影响0人  喜剧之王爱创作
timg.jpg
在前端开发中,我们经常会遇到点击按钮后,需要等待n秒后才可再次进行点击。比如我们看到的
微信图片_20191118195316.png
假如只是单个这样的倒计时操作按钮,我们或许不废吹灰之力就可写成,可是有时候我们会遇到这种情况
微信图片_20191118195558.png
我们想要实现一个这样的列表上的按钮,且有各自的计时和事件,一般会直接操作数据简单暴力,给数据中加一个诸如isLoading这样的属性,通过遍历时判断其真假,来实现其是否警用,或许你还得单独去维护一个计时按钮什么鬼的来实现,可能会比较繁琐,当然,肯定是能实现的。

看这里!

小编业余时间,遇到群友提问,遍帮他封装了一个组件,我将它分享给大家。

import React, { PureComponent } from 'react'
import { Button } from 'antd'

class LoadingButton extends PureComponent {
    buttonWidth = {
        width: '100px',
    }

    static defaultProps = {
        waitTime: 60,
        text: '操作',
    }

    constructor(props) {
        super(props)
        this.state = {
            count: this.props.waitTime,
            loading: false,
        }
    }

    buttonCallback = () => {
        this.props.onClick()
        this.setState({
            loading: true,
            count: this.props.waitTime,
        })
        const countChange = setInterval(() => {
            const { count } = this.state
            const newData = count
            this.setState({
                count: newData - 1,
            }, () => {
                if (this.state.count === 0) {
                    clearInterval(countChange)
                    this.setState({
                        loading: false,
                    })
                }
            })
        }, 1000)
    }

    render() {
        const { loading, count } = this.state
        const { text } = this.props
        return (
        loading ? <Button style={this.buttonWidth} disabled >({count}s)后操作</Button> : <Button style={this.buttonWidth} type="primary" onClick={this.buttonCallback}>{text}</Button>
        )
    }
}

这是组件的源码,感兴趣的同学可以对其做优化,并私信我做出改正

怎么使用?

使用起来就非常简单了,看过源码的同学已经发现本组件只接受三个参数

使用的时候我么只需要向下面这样传参就好了。你甚至只需要复制粘贴上面的源码到你的项目中

                <LoadingButton
                    onClick={() => { this.buttonClick(record) }}// 点击按钮的回调
                    text="操作"// 按钮文字
                    waitTime={60}// 等待时间
                />

写在后面

这样在实现如上面列表中的独立的操作倒计时功能就不需要操作表格数据了。
试一下吧!
感谢您的支持,有问题可私信联系。

上一篇 下一篇

猜你喜欢

热点阅读