最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Continuously increasing counter with long press React Native - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question asked Jul 12, 2016 at 16:41 rikesanrikesan 1631 silver badge7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

I 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 onPressInand 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.

发布评论

评论列表(0)

  1. 暂无评论