Created
May 30, 2018 10:12
-
-
Save ivmos/b6546de193349fcf54ea8581ea445a8d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import { TouchableOpacity, TouchableHighlight } from 'react-native'; | |
import { PropTypes } from 'prop-types'; | |
/* eslint-disable no-invalid-this */ | |
const debounce = function(callback, wait, context = this) | |
{ | |
let timeout = null; | |
let callbackArgs = null; | |
const later = () => callback.apply(context, callbackArgs); | |
return function() | |
{ | |
/* eslint-disable prefer-rest-params */ | |
callbackArgs = arguments; | |
clearTimeout(timeout); | |
timeout = setTimeout(later, wait); | |
}; | |
}; | |
/** | |
* Based on https://medium.com/@devmrin/debouncing-touch-events-in-react-native-prevent-navigating-twice-or-more-times-when-button-is-90687e4a8113, | |
* just made it more generic | |
*/ | |
export default class TouchableDebounce extends Component | |
{ | |
constructor(props) | |
{ | |
super(props); | |
} | |
render() | |
{ | |
const TouchableComponent = this.props.type == 'Opacity' | |
? TouchableOpacity | |
: TouchableHighlight; | |
return ( | |
<TouchableComponent | |
style={this.props.style} | |
accessibilityLabel={this.props.accessibilityLabel} | |
raised={this.props.raised} | |
underlayColor={this.props.underlayColor} | |
activeOpacity={this.props.activeOpacity} | |
onPress={ | |
debounce(() => | |
{ | |
this.props.onPress(); | |
}, 500) | |
} | |
> | |
{this.props.children} | |
</TouchableComponent> | |
); | |
} | |
} | |
TouchableDebounce.propTypes = | |
{ | |
accessibilityLabel : PropTypes.any, | |
raised : PropTypes.any, | |
underlayColor : PropTypes.any, | |
children : PropTypes.any, | |
type : PropTypes.string, | |
style : PropTypes.any, | |
activeOpacity : PropTypes.any, | |
onPress : PropTypes.string | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment