让用户不参与反应本机

ton*_*sta 6 react-native

我要显示的是如果用户在1分钟内未与应用程序进行交互的图像。我尝试通过在所有元素上的所有用户事件(如onPress onSwipe等)上设置计时器来实现它。但是处理这些是一个复杂的过程。然后,我尝试使用InteractionManager尝试了一下,但也没有解决。我想知道有什么办法可以知道是否发生了任何用户事件?

ton*_*sta 6

最后,我使用PanResponder做到了。而且它可以完美地工作。它需要按键和滑动。

博览会链接: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',
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 在每个组件中执行此操作可能会导致非常奇怪的行为,具体取决于您在应用中处理导航的方式。在不知道的情况下,您可能会生成多个计时器(每次导航到一个新组件时一个)。我使用的是反应导航,所以我创建了一个自定义导航器 (https://reactnavigation.org/docs/en/custom-navigators.html) 来包装我想要检查不活动的屏幕的 StackNavigator。 (2认同)