0

我在网上找到了例子:

https://snack.expo.io/Sy8ulr8B-

主要概念是在每个组件中应用此代码:

this._panResponder = PanResponder.create({
  onStartShouldSetPanResponder: () => {
    this.resetTimer()
    return true
  },
  onMoveShouldSetPanResponder: () => true,
  onStartShouldSetPanResponderCapture: () => { this.resetTimer() ; return false},
  onMoveShouldSetPanResponderCapture: () => false,
  onPanResponderTerminationRequest: () => true,
  onShouldBlockNativeResponder: () => false,
});
4

1 回答 1

0

**我找到了答案:**

import React, { Component } from 'react';
import { Button, PanResponder, View, StyleSheet,TouchableOpacity, Text , Image, Alert} from 'react-native';

const timeNoAction = 15000;

export default class Screen extends Component {
  state = {
    show : false
  };
  _panResponder = {};
  timer = 0;
  componentWillMount() {
    this._panResponder = PanResponder.create({

      onStartShouldSetPanResponder: () => {
        this.resetTimer()
        return true
      },
      onMoveShouldSetPanResponder: () => true,
      onStartShouldSetPanResponderCapture: () => { this.resetTimer() ; return false},
      onMoveShouldSetPanResponderCapture: () => false,
      onPanResponderTerminationRequest: () => true,
      onShouldBlockNativeResponder: () => false,
    });
    this.timer = setTimeout(()=>this.setState({show:true}),timeNoAction )
  }

  resetTimer(){
    clearTimeout(this.timer)
    if(this.state.show)
    this.setState({show:false})
    this.timer = setTimeout(()=>this.setState({show:true}),timeNoAction )
  }

  render() {
    return (
      <View
        style={styles.container}
        collapsable={false}
        {...this._panResponder.panHandlers}>

        {
          this.state.show ? Alert.alert(
            'Alert',
            'You have been inactive for 15sec',
            [
              {text: 'OK', onPress: () => this.resetTimer()},
            ],
            { cancelable: false }
          ) : null
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  }
});

}
于 2021-11-17T12:29:42.893 回答