setParams
스택 네비게이션 예시
- HomeScreen → Profile로 전환 시
friends: ['Brent', 'Satya', 'Michaś'],
title: "Brent's Profile",
- Profile에서 버튼 클릭 시
setParams
로 현재 스크린의 프롭 변경됨.
friends: ['Wojciech', 'Szymon', 'Jakub'],
title: "Lucy's Profile",
코드
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function HomeScreen({ navigation: { navigate } }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>This is the home screen of the app</Text>
<Button
onPress={() =>
navigate('Profile', {
friends: ['Brent', 'Satya', 'Michaś'],
title: "Brent's Profile",
})
}
title="Go to Brent's profile"
/>
</View>
);
}
function ProfileScreen({ navigation, route }) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Profile Screen</Text>
<Text>Friends: </Text>
<Text>{route.params.friends[0]}</Text>
<Text>{route.params.friends[1]}</Text>
<Text>{route.params.friends[2]}</Text>
<Button
onPress={() =>
navigation.setParams({
friends:
route.params.friends[0] === 'Brent'
? ['Wojciech', 'Szymon', 'Jakub']
: ['Brent', 'Satya', 'Michaś'],
title:
route.params.title === "Brent's Profile"
? "Lucy's Profile"
: "Brent's Profile",
})
}
title="Swap title and friends"
/>
<Button title="Go back" onPress={() => navigation.goBack()} />
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen
name="Profile"
component={ProfileScreen}
options={({ route }) => ({ title: route.params.title })}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;