如何知道react native每个组件的屏幕空闲状态?

bf1o4zei  于 2023-03-19  发布在  React
关注(0)|答案(1)|浏览(141)

我在网上找到了一些例子:
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,
});
n9vozmp4

n9vozmp41#

我找到了答案:

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',
  }
});

}

相关问题