在由堆栈导航器托管的屏幕内访问`headerRight`

时间:2020-08-28 14:48:02

标签: react-native react-navigation react-native-navigation

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

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

const TheStack = createStackNavigator();

然后,这是我的导航器,它声称component={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` component I have set above from here? 
   ...
}

我的问题是如何访问 LandingScreen.js 中的headerRight?我知道我可以通过以下方式更新或重置headerRight

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

但是现在我需要访问的是先前已设置的组件,而不是设置新的组件。该怎么做?

1 个答案:

答案 0 :(得分:0)

根据评论中收到的请求编辑答案。答案是一样的。这只是如何使用它的进一步说明。

// The screen component where you want to pass the state.

const Screen = (props) => {
  const [color, setColor] = useState("#CCCCCC");

  const { navigation } = props //This is important or else UseEffect will be called each time any of the props change

  useEffect(() => {
    navigation.setParams({ color: color }); // Where its being passed.
  }, [color, navigation]);

  return (
   <>
    <Button onPress={() => setColor("#800000")} /> // Change the color state to Maroon
    <Button onPress={() => setColor("#FED700")} /> // Change the color state to Gold
   </>
  )
}

您的标题组件:

const MyHeaderComponent = (props) {
  return(
    <View style={{ backgroundColor: props.bgColor }} />
  )
}

然后您可以在headerRight中检索此位。像这样:

headerRight:() => <MyHeaderComponent bgColor={route.params.color} />


注意:该方法对React Navigation v5有效。版本4具有getParams()函数来检索参数,但在版本5中已将其删除。


原始答案

您可以在屏幕上创建一个useState挂钩,并将其值传递到标题组件中。因此,当标题组件更新状态时,可以在定义状态的屏幕内对其进行访问。

您可以使用setParams()函数设置要在标头组件中使用的参数。然后,使用route.params.nameofyourprop将其获取到headerComponent中,以便在其中使用它。

这是将参数从标头外部传递到标头内部。

headerRight:() => <MyHeaderRightComponent propname={route.params.propvalue} />

用于从标头外部设置参数,您可以在headerRight组件内部访问该参数。

const [values, setValue] = useState()

navigation.setParams({propname: value})

这样,您可以在标题和屏幕之间传递状态。

您也可以通过这种方式传递useState的setValue函数,但是它会引发警告,因为函数是Javascript中的对象,因此无法对其进行索引...或这些行中的内容。