I have a button next to a TextInput
that increases its counter when pressed.
<TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
<View style={styles.amountPlusButtonContainer}>
<Text style={styles.amountButtonText}>+</Text>
</View>
</TouchableWithoutFeedback>
It currently increases by 1 each time I tap the button. What I want to achieve is to keep increasing the counter for as long as the user is pressing it.
I have tried to use setInterval()
but I don't know exactly when to stop it nor if it's the right approach to this problem.
I have a button next to a TextInput
that increases its counter when pressed.
<TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
<View style={styles.amountPlusButtonContainer}>
<Text style={styles.amountButtonText}>+</Text>
</View>
</TouchableWithoutFeedback>
It currently increases by 1 each time I tap the button. What I want to achieve is to keep increasing the counter for as long as the user is pressing it.
I have tried to use setInterval()
but I don't know exactly when to stop it nor if it's the right approach to this problem.
2 Answers
Reset to default 5I think to use setInterval
is a good solution.
Call setInterval
on onPressIn and clearInterval
on onPressOut.
I was able to make it work using the Animated
API. A reference I used (besides the official documentation) was http://browniefed./blog/react-native-press-and-hold-button-actions/
var ACTION_TIMER = 3000;
var listenerActive = true;
getInitialState(){
return{
pressAction: new Animated.Value(0),
value: 0,
};
},
ponentWillMount: function() {
this.state.pressAction.addListener((v) => this.setState({value: v.value}));
},
handlePressIn: function() {
if(!listenerActive) {
this.state.pressAction.addListener((v) => this.setValueAndChangeAmount(v.value));
listenerActive = true;
}
Animated.timing(this.state.pressAction, {
duration: ACTION_TIMER,
toValue: 67,
}).start();
},
handlePressOut: function() {
this.state.pressAction.removeAllListeners();
this.setState({pressAction: new Animated.Value(Math.ceil(this.state.value))});
listenerActive = false;
},
I used 3000ms and Math.ceil to maintain the same behavior as onPress
since it cannot be used alongside onPressIn
and onPressOut
.
Removing the listener in handlePressOut
stops the counter. Setting a new pressAction
with this.state.value
resets the value to the one the counter stopped at.