【问题标题】:Continuously increasing counter with long press React Native长按 React Native 不断增加计数器
【发布时间】:2016-07-12 16:41:10
【问题描述】:

我在TextInput 旁边有一个按钮,按下时会增加计数器。

   <TouchableWithoutFeedback onPress={() => {this.increaseAmount(step, rowID)}}>
      <View style={styles.amountPlusButtonContainer}>
        <Text style={styles.amountButtonText}>+</Text>
      </View>
    </TouchableWithoutFeedback>

目前每次点击按钮时它都会增加 1。我想要实现的是只要用户按下它就不断增加计数器。

我曾尝试使用setInterval(),但我不知道何时停止它,也不知道这是否是解决此问题的正确方法。

【问题讨论】:

    标签: javascript android ios react-native


    【解决方案1】:

    我认为使用setInterval 是一个很好的解决方案。 致电setInterval onPressInclearInterval onPressOut

    【讨论】:

    【解决方案2】:

    我能够使用Animated API 使其工作。我使用的参考(除了官方文档)是http://browniefed.com/blog/react-native-press-and-hold-button-actions/

       var ACTION_TIMER = 3000;
       var listenerActive = true;
    
       getInitialState(){
         return{
           pressAction: new Animated.Value(0),
           value: 0,
         };
       },
       componentWillMount: 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;
       },
    

    我使用 3000ms 和 Math.ceil 来保持与 onPress 相同的行为,因为它不能与 onPressInonPressOut 一起使用。

    删除handlePressOut 中的侦听器会停止计数器。使用this.state.value 设置新的pressAction 会将值重置为计数器停止的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 2020-12-20
      • 2016-02-07
      • 2018-12-22
      相关资源
      最近更新 更多