美文网首页RN知识
React-Native 防止按钮重复点击

React-Native 防止按钮重复点击

作者: 精神病患者link常 | 来源:发表于2018-11-13 17:34 被阅读45次
    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>
    

    相关文章

      网友评论

        本文标题:React-Native 防止按钮重复点击

        本文链接:https://www.haomeiwen.com/subject/wnblfqtx.html