在由堆栈导航器托管的屏幕内更新“ headerRight” 示例

问题描述

我创建了一个堆栈导航器:

import {createStackNavigator} from '@react-navigation/stack';

const TheStack = createStackNavigator();

然后,在此导航器下有一个LandingScreen

<TheStack.Navigator ...>
  <TheStack.Screen
        name="LandingScreen"
        component={LandingScreen}
        options={{
          title: '',headerLeft: null,headerRight: () => (
            <MyHeaderRightComponent />
          ),}}
      />

<TheStack.Navigator>

正如您在屏幕的options上方看到的那样,有headerRight,我已经声明将MyHeaderRightComponent用作headerRight,以便它显示在右侧屏幕上的标题

这是我的LandingScreen.js

import React,{useState} from 'react';
import {View,StyleSheet} from 'react-native';

const LandingScreen = ({navigation}) => {
   // How can I access the `headerRight` here to update the `headerRight` to another component? 
   ...
}

我的问题是如何访问 LandingScreen.js 中的headerRight,以便更新headerRight以便在标头上显示其他组件?

解决方法

我最近遇到了一个类似的问题,即我不得不在屏幕内更改标题标题。可以通过navigation.setOptions()完成。

示例

这应该在您的LandingScreen组件中。

navigation.setOptions({headerRight:() => <NewHeaderRightComponent/>})