1. 程式人生 > >React Native TouchableOpacity 封裝 防止快速點選 多次響應

React Native TouchableOpacity 封裝 防止快速點選 多次響應

不耽誤幹活,直接上程式碼,功能比較簡單,具體延時時間自己定,還需要啥功能自己改進一下。

import React,{ Component } from "react";
import {TouchableOpacity, View} from "react-native";

class Button extends React.Component<ButtonProps, any> {
    constructor(props) {
        super(props)
        this.state = {
            disabled: true
        }
        this.lastClickTime=0
    }

    onPress () {
        const clickTime = Date.now()
        if (!this.lastClickTime || Math.abs(this.lastClickTime - clickTime) > 350) {  //350的時間可以延長,根據需要改變
            this.lastClickTime = clickTime
            if(this.props.onPress){
                this.props.onPress()
            }else{
                return ''
            }

        }
    }

    render() {
        return (
            <TouchableOpacity
                onPress={this.onPress.bind(this)}
                activeOpacity={this.props.activeOpacity || 0.85}
                style={this.props.style}
                disabled={this.props.disabled}
            >
                {this.props.children}
            </TouchableOpacity>)
    }
}

export default Button