尝试title
在 React Navigation 6 中动态设置标题,但我不断收到警告消息:
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,
})
根据有关使用更新选项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
研究:
title
一切都在我的 Expo 应用程序中正常工作,但我不确定组件是否根据从道具传递的选择来设置类别 ID如果我无法从导航器的堆栈屏幕上设置标题,我该如何动态设置?