【发布时间】:2022-01-14 18:11:21
【问题描述】:
尝试在 React Navigation 6 中动态设置标题的 title,但我不断收到警告消息:
警告:无法更新组件 (
NativeStackNavigator) 渲染不同的组件 (CategoryMealsScreen)
我的导航器被拆掉了:
import * as React from 'react'
import { Platform } from 'react-native'
import { NavigationContainer } from '@react-navigation/native'
import { createNativeStackNavigator } from '@react-navigation/native-stack'
import CategoryMealsScreen from '../screens/CategoryMealsScreen'
import colors from '../constants/colors'
const Stack = createNativeStackNavigator()
export default MealsNavigator = () => {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerStyle: {
backgroundColor: Platform.OS === 'android' ? colors.primaryColor : '',
},
headerTintColor: Platform.OS === 'android' ? 'white' : colors.primaryColor,
}}
>
<Stack.Screen
name="CategoryMeals"
component={CategoryMealsScreen}
options={{ headerBackTitle: '' }}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
我如何在组件中设置title:
navigation.setOptions({
title: selectedCategory.title,
})
根据Updating options with setOptions 上的文档。完整组件供参考:
import React from 'react'
import { View, StyleSheet, FlatList } from 'react-native'
import MealItem from '../components/MealItem'
import { CATEGORIES, MEALS } from '../data/dummy-data'
const CategoryMealsScreen = ({ navigation, route }) => {
const catId = route.params.categoryId
const selectedCategory = CATEGORIES.find(cat => cat.id === catId)
const displayedMeals = MEALS.filter(mean => mean.categoryIds.indexOf(catId >= 0))
// Issue falls here
navigation.setOptions({
title: selectedCategory.title,
})
const renderMealItem = ({ item }) => {
return (
<MealItem
title={item.title}
image={item.imageUrl}
duration={item.duration}
complexity={item.complexity}
affordability={item.affordability}
onSelectMeal={() => {
navigation.navigate('MealDetail', {
mealId: item.id,
})
}}
/>
)
}
return (
<View style={styles.container}>
<FlatList
keyExtractor={item => item.id}
data={displayedMeals}
renderItem={renderMealItem}
style={{ width: '100%' }}
/>
</View>
)
}
const styles = StyleSheet.create({
screen: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 15,
},
})
export default CategoryMealsScreen
研究:
- Dynamically change header title in react native navigation
- React-Native, Dynamic ReactNavigation title
- Unable to set header title dynamically in react native
在我的 Expo 应用程序中一切正常,但我不确定组件是否根据从道具传递的选择来设置类别 ID 如果我无法在导航器的堆栈屏幕上设置标题,如何动态设置 title ?
【问题讨论】:
标签: react-native expo react-navigation react-navigation-stack react-navigation-v6