如果用户没有点击或对其执行任何操作,我需要在我的应用中显示一条消息。例如:
if (timeNoAction = 15s){
alert('tap')
}
答案 0 :(得分:1)
您必须使用PanResponder:
以下是代码示例:
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',
}
});
}
您可以在App.js
中设置它,在任何组件或整个应用中使用它快乐编码:)
答案 1 :(得分:1)
使用react-native-interaction-provider
这是一个检测用户交互的行为组件包装器,让您知道应用程序何时闲置。
import InteractionProvider from 'react-native-interaction-provider'
<InteractionProvider
timeout={15 * 1000} // idle after 15s
onActive={() => console.log('User no longer idle')}
onInactive={() => console.log('User is idle for 15s')}
>
<YourScreen />
</InteractionProvider>