让用户在 React Native 中处于非活动状态 [英] get user inactivity in react native
问题描述
如果用户在 1 分钟内没有与应用交互,我想要显示一个图像.我尝试通过在所有元素上的所有用户事件(如 onPress onSwipe 等)上设置计时器来实现它.但处理这些是一个复杂的过程.然后我尝试使用 InteractionManager 但这也没有奏效.我想知道有什么方法可以知道是否发生了任何用户事件?
What I want is to display a Image if user does not interact with the app for 1 minute. I have tried implementing it by setting timers on all the user events like onPress onSwipe etc on all the elements. But handling those is a complex process. Then I tried out using InteractionManager but that also didn't work out. What I want to know is there any way I can get to know if any user event has occurred?
推荐答案
最后,我使用 PanResponder 做到了.它完美无缺.它需要按键、滑动和拖动.
Finally, I did it using PanResponder. And It works flawlessly. It takes key presses ans swipes and drags.
展会链接:https://snack.expo.io/Sy8ulr8B-
这是我的代码:
import React, { Component } from 'react';
import { Button, PanResponder, View, StyleSheet,TouchableOpacity, Text , Image} from 'react-native';
export default class App 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}),5000)
}
resetTimer(){
clearTimeout(this.timer)
if(this.state.show)
this.setState({show:false})
this.timer = setTimeout(()=>this.setState({show:true}),5000)
}
render() {
return (
<View
style={styles.container}
collapsable={false}
{...this._panResponder.panHandlers}>
{
this.state.show ? <Text style={{fontSize:30}}>Timer Expired : 5sec</Text> : null
}
<TouchableOpacity>
<Image style={{width: 300, height: 300}} source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} />
</TouchableOpacity>
<Button
title="Here is a button for some reason"
onPress={() => {}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
}
});
这篇关于让用户在 React Native 中处于非活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!