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

Javascript 如何在React中从堆栈调用导航事件?,javascript,reactjs,react-native,react-navigation,Javascript,Reactjs,React Native,React Navigation,当我离开StackNavigator中第二个名为GridVid的屏幕时,我想调用NavigationEvent函数onWillBlur() 因此,在我的SettingsClass中,堆栈中的第一个屏幕,这很好,我可以调用onWillBlur(),因为它在App.js文件中 但是,尝试在堆栈的第二个屏幕(称为GridVid,在GridVid.js文件中定义)中调用onWillBlur()不起作用。我怎样才能解决这个问题 //App.js class SettingsClass extends Co

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

因此,在我的SettingsClass中,堆栈中的第一个屏幕,这很好,我可以调用onWillBlur(),因为它在App.js文件中

但是,尝试在堆栈的第二个屏幕(称为GridVid,在GridVid.js文件中定义)中调用onWillBlur()不起作用。我怎样才能解决这个问题

//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
      }
   })
类设置类扩展组件{
render(){
返回(
{
警报(“从设置中移动”)//这工作正常!!!
}}
/>
)
}
} 
//屏幕底部的选项卡
const TabNavigator=createBottomTabNavigator(
{
主屏幕:{
屏幕:HomeClass,
},
设置策略
},
)
//设置类滑动到GridVid
const SettingsStack=createStackNavigator({
设置屏幕:{
屏幕:设置类别
},
GridVid:{
屏幕: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> 
    );
 }
}
导出默认类GridVidClass扩展组件{
render(){
返回(
上网
{
警报('moving from GridVid')//这不起作用。。。
}}
/>
);
}
}

尝试使用Event addListener。它可以解决这个问题

埃克斯马普


建造师(道具){
超级(道具);
this.willBlur=props.navigation.addListener(
“willBlur”,
() => {
警报(“从GridVid移动”);
}
);
}
组件将卸载(){
this.willBlur.remove();
}
并且,使用
push
命令渲染屏幕

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

谢谢。这很有效。我只需要在构造器中的willBlur和willFocus中设置state。不需要再推另一个屏幕。