RN知识

React-Native 防止按钮重复点击

2018-11-13  本文已影响45人  精神病患者link常
import React, {PureComponent} from 'react';
import {
    TouchableOpacity
} from "react-native"
import PropTypes from 'prop-types'
import throttle from 'lodash.throttle';

export default class Touchable extends PureComponent {

    constructor(props){
        super(props)
        this.handleClickThrottled = throttle(this.props.onPress, this.props.onPressWithSecond);
    }
    componentWillUnmount() {
        this.handleClickThrottled.cancel();
    }

    render() {
        return (
            <TouchableOpacity {...this.props} onPress={this.handleClickThrottled}>
                {this.props.children}
            </TouchableOpacity>
        );
    }
}

Touchable.propTypes = {
    onPressWithSecond: PropTypes.number, // 几秒钟可以点击一次
}

Touchable.defaultProps = {
    onPressWithSecond: 1000
}

使用

当做 TouchableOpacity 使用即可

<Touchable onPressWithSecond={3000}
                   onPress={()=>{
                     ...
                   }}
               >
                   <Text>Click to test double click!</Text>
                  
               </Touchable>
上一篇下一篇

猜你喜欢

热点阅读