在React Navigation中,无状态组件(也称为函数式组件)可以使用navigationOptions
来设置导航栏的标题、按钮等。从React Navigation 5.0开始,navigationOptions
已经被移除,取而代之的是使用screenOptions
和组件内的options
属性。
以下是如何在无状态组件上设置navigationOptions
的示例:
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
type StackParamList = {
Home: undefined;
Details: { itemId: number };
};
const Stack = createStackNavigator<StackParamList>();
const HomeScreen = ({ navigation }: { navigation: any }) => {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details', { itemId: 42 })}
/>
</View>
);
};
HomeScreen.options = {
title: 'Home',
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
const DetailsScreen = ({ route }: { route: any }) => {
const { itemId } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen for item {itemId}</Text>
</View>
);
};
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
如果你仍然在使用React Navigation 4.x,可以在无状态组件中这样设置navigationOptions
:
import React from 'react';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
type StackParamList = {
Home: undefined;
Details: { itemId: number };
};
const Stack = createStackNavigator<StackParamList>({
Home: {
screen: HomeScreen,
navigationOptions: {
title: 'Home',
headerStyle: {
backgroundColor: '#f4511e',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
},
},
Details: {
screen: DetailsScreen,
},
});
const HomeScreen = ({ navigation }: { navigation: any }) => {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Details', { itemId: 42 })}
/>
</View>
);
};
const DetailsScreen = ({ route }: { route: any }) => {
const { itemId } = route.params;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen for item {itemId}</Text>
</View>
);
};
const AppContainer = createAppContainer(Stack);
export default AppContainer;
options
属性直接在组件上设置导航选项。navigation
对象通过组件的参数传递。createStackNavigator
中直接设置每个屏幕的navigationOptions
。navigation
对象同样通过组件的参数传递。通过这种方式,你可以在无状态组件上设置导航选项,从而自定义导航栏的外观和行为。
领取专属 10元无门槛券
手把手带您无忧上云