简体   繁体   English

如何动态更新 React-Navigation 中的 header

[英]How to update header in React-Navigation dynamically

I am using React-Navigation v-5.我正在使用 React-Navigation v-5。 I want to update the header dynamically directly from the screen but I am unable to do it.我想直接从屏幕上动态更新 header 但我做不到。 Here is my code, I am using a slightly different logic here.这是我的代码,我在这里使用了稍微不同的逻辑。 First I create the stack of screens in a different file name MealsNavigator.首先,我在不同的文件名 MealsNavigator 中创建屏幕堆栈。

export default function MealsNavigator() {
    const Stack = createStackNavigator();

    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="Categories" component={Categories} />
                <Stack.Screen name="MealsCategory" component={CategoryMeal} />
                <Stack.Screen name="MealDetails" component={MealDetails} />
            </Stack.Navigator>
        </NavigationContainer>
  );
}

Then, I pass the props in each screen like this,然后,我像这样传递每个屏幕中的道具,

export default function CategoryMeal(props){}

Then I used this props to navigate between screens like this,然后我用这个道具在这样的屏幕之间导航,

<Button title = 'Go to Meal Details!' onPress = {() => {
        props.navigation.navigate('MealDetails')
      }}/>

This works fine but when it comes to updating the header, I stuck.这工作正常,但在更新 header 时,我卡住了。 I don't know what to do.我不知道该怎么办。 I want to add these things into my Category screen header我想将这些东西添加到我的类别屏幕 header

 headerTitle: 'Meal Categories',
  headerStyle: {
    backgroundColor: Colors.primaryColor  
  },
  headerTintColor:'#ffffff' 

And here is my Category screen code,这是我的类别屏幕代码,

export default function Categories(props){
  const renderGridItem = (itemData) => {
    return(
      <TouchableOpacity
      style = {styles.gridItem} 
      onPress = {() => {
        props.navigation.navigate('MealsCategory', {
          categoryID: itemData.item.id,           
        })
      }}>
        <View >
          <Text>
            {itemData.item.title}
          </Text>
        </View>
      </TouchableOpacity>
    )
  }
  return(
    <FlatList
    data = {CategoriesData}
    renderItem = {renderGridItem}
    numColumns = {2}
    />
  )
}

I already tried these options Categories.props.navigation.setOptions, props.navigation.setOptions, props.navigation.options but none of them are working.我已经尝试过这些选项Categories.props.navigation.setOptions, props.navigation.setOptions, props.navigation.options但它们都不起作用。

I will be extremely thankful if someone will help me.如果有人帮助我,我将非常感激。

It's Done.完成。 It is needed to done like it需要这样做

useLayoutEffect(() => {
  props.navigation.setOptions({
    headerTitle: 'Meal Categories',
  headerStyle: {
    backgroundColor: Colors.primaryColor  
  },
  headerTintColor:'#ffffff' 
  })
})

Thanks!谢谢!

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

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