简体   繁体   中英

React Navigation - Listen parent action in child component

I have a tab navigator Screen in which there are 2 tabs. The parent Stack has button in the header, which should work differntly w.r.t Two different screens/Tabs.

在此处输入图像描述

Now, What I have done is -

navigation.setOptions({
  headerRight: () => (
    <TouchableOpacity>
      <Text>Update</Text>
    </TouchableOpacity>
  ),
});

How I can handle the click of Save button from both the components under Tabs Navigator?

Note - I am using react-navigation@v6

Here, I want to give the answer of my question myself.

The solution is to not set the Navigation right button from Parent navigator, Access the parent navigation from each Tab screen and set the Right header.

Also you should use useFocusEffect to add this because it can be different for different tabs of the navigator. Here's how you can do it -

import { useFocusEffect } from '@react-navigation/native';

useFocusEffect(() => {
    navigation.getParent().setOptions({
      headerRight: () => (
        <TouchableOpacity 
          disabled={true}
          style={styles.headerRight}>
          <Text style={{ color: 'black' }}>Save</Text>
        </TouchableOpacity>
      ),
    });
});

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