简体   繁体   English

React Navigation - 在子组件中监听父动作

[英]React Navigation - Listen parent action in child component

I have a tab navigator Screen in which there are 2 tabs.我有一个选项卡导航器屏幕,其中有 2 个选项卡。 The parent Stack has button in the header, which should work differntly w.r.t Two different screens/Tabs.父堆栈在 header 中有按钮,它应该以不同的方式工作 w.r.t 两个不同的屏幕/选项卡。

在此处输入图像描述

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?我如何处理 Tabs Navigator 下两个组件的Save按钮的单击?

Note - I am using react-navigation@v6注意- 我正在使用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.解决方案是不从父导航器设置导航右按钮,从每个选项卡屏幕访问父导航并设置右 header。

Also you should use useFocusEffect to add this because it can be different for different tabs of the navigator.您还应该使用useFocusEffect添加它,因为它对于导航器的不同选项卡可能不同。 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>
      ),
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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