如何在React中从堆栈调用导航事件?

时间:2019-07-29 19:26:15

标签: javascript reactjs react-native react-navigation

当我离开StackNavigator第2个名为GridVid的屏幕时,我想在onWillBlur()上调用NavigationEvent函数。

因此,在我的SettingsClass(堆栈的第一个屏幕)中,此方法工作正常,我可以调用onWillBlur(),因为它位于App.js文件中。

但是,尝试在堆栈的第二个屏幕中调用onWillBlur()(称为GridVid,在GridVid.js文件中定义)无效。我该如何解决?

// App.js

class SettingsClass extends Component {

    render() {
          return (
            <View style={styles.settingsContainer}>
               <NavigationEvents
                       onWillBlur={() => {
                           alert('moving from Settings') //THIS WORKS FINE!!!
                       }}
              />
            </View>
            )
          }
   } 


    //Tabs across the bottom of the screen
    const TabNavigator = createBottomTabNavigator(
      {
        HomeScreen: { 
            screen: HomeClass,
        },

        SettingsStack
      },
    )

    //Settings Class swipes to GridVid
    const SettingsStack = createStackNavigator({
      SettingsScreen: {
        screen: SettingsClass
      },
      GridVid: {
        screen: GridVidClass
      }
   })

// GridVid.js

export default class GridVidClass extends Component {

  render() {
   return (
    <View style={styles.container}> 
         <Text>On Grid </Text>

         <NavigationEvents
           onWillBlur={() => {
               alert('moving from GridVid')  //THIS DOESN'T WORK...
           }}
      />

    </View> 
    );
 }
}

1 个答案:

答案 0 :(得分:1)

尝试使用事件addListener。它可以解决问题。

例如


  constructor(props) {
    super(props);
 this.willBlur = props.navigation.addListener(
    'willBlur',
    () => {
       alert('moving from GridVid');
    }
  );
}

  componentWillUnmount() {
    this.willBlur.remove();

  }

然后,使用push命令渲染屏幕。

this.props.navigation.push('Gridvid');