简体   繁体   中英

Using ex-navigation with Exponent js, how do I clear the StackNavigation of a tab when the user navigates away?

I'm using ex-navigation with Exponent and React Native. I have a multi-tab TabNavigation, where each tab has its own StackNavigation element inside. When the user changes tabs in the TabNavigation, I'd like to reset the stack of the previous tab.

I can already reset the StackNavigation element using popToTop , but my issue is determining when the user changes tabs. Is there an emitted tab-change event, or route change event, that I can subscribe to?

After some help from the ex-navigation developers, I have found a way to clear the tab stack upon navigating away. We can attach an onPress handler to the TabNavigation component, and it will be passed the default event handler. After calling the default handler to change tabs, we can perform any other desired actions. Here's a version of a TabNavigation that clears the stack of the first tab when the user clicks any of the tabs:

export default class RootNavigation extends React.Component {
  constructor(props) {
    super(props);
    this.onPress = this.onPress.bind(this);
  }

  onPress(switchTab) {
    switchTab();
    requestIdleCallback(() => {
      this.props.navigation.performAction(({stacks}) => {
        stacks("first").popToTop();
      });
    });
  }

  render() {
    return (
      <View>
        <TabNavigation initialTab="first">
          <TabNavigationItem id="first-tab" onPress={this.onPress}>
            <StackNavigation id="first" navigatorUID="first" initialRoute="first-route" />
          </TabNavigationItem>

          <TabNavigationItem id="second-tab" onPress={this.onPress}>
            <StackNavigation id="second" navigatorUID="second" initialRoute="second-route" />
          </TabNavigationItem>

          <TabNavigationItem id="third-tab" onPress={this.onPress}>
            <StackNavigation id="third" navigatorUID="third" initialRoute="third-route" />
          </TabNavigationItem>
        </TabNavigation>
      </View>
    );
  }
};

Note that the stack we manipulate through stacks("first") must have both an id and navigatorUID set to "first" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM