npm install @react-navigation/native @react-navigation/native-stack
기본 앱
npm install react-native-screens react-native-safe-area-context
createNativeStackNavigatorScreen및 Navigator 을 반환하는 함수이다.NavigationContainerStack.NavigatorinitialRouteName 를 통해 기본 페이지를 설정할 수 있다.navigation.navigateStack.Screenname 은 대문자로 하는것이 일반적이다 name="Home"
name, component가 기본으로 들어가야 한다. component={HomeScreen}
화면별 옵션을 지정할 때에는 options={{ title: 'Overview' }} 를 통해 전달이 가능하다. (상단에 페이지 제목으로 들어가는 문자열이 된다)
Stack.Screen 으로 화면을 정의할 수 있다.
onPress ⇒ navigation.navigate('Profile') 로 페이지 전환 가능하다.
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
const MyStack = () => {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Welcome' }}
/>
<Stack.Screen name="Profile" component={ProfileScreen} />
</Stack.Navigator>
</NavigationContainer>
);
};
const HomeScreen = ({ navigation }) => {
return (
<Button
title="Go to Jane's profile"
onPress={() =>
navigation.navigate('Profile', { name: 'Jane' })
}
/>
);
};
const ProfileScreen = ({ navigation, route }) => {
return <Text>This is {route.params.name}'s profile</Text>;
};
navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
<Stack.Screen
name="Details"
component={DetailsScreen}
initialParams={{ itemId: 42 }}
/>
//Page2
navigation.navigate({
name: 'Home',
params: { post: postText },
merge: true,
});
//입력값을 post:postText에 담아서 이전 페이지로 전달한다.
//Home 에서 사용한다
React.useEffect(() => {
if (route.params?.post) {
// Post updated, do something with `route.params.post`
// For example, send the post to the server
}
}, [route.params?.post]);
<Text style={{ margin: 10 }}>Post: {route.params?.post}</Text>
function Home() {
return (
<Tab.Navigator>
<Tab.Screen name="Feed" component={Feed} />
<Tab.Screen name="Messages" component={Messages} /> // --->Home안에 다른 페이지 중첩
</Tab.Navigator>
);
}
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
options={{ headerShown: false, animationEnabled:false
//상단바 안보이게, 에니메이션 효과 false
}}
/>
<Stack.Screen name="Profile" component={Profile} />
<Stack.Screen name="Settings" component={Settings} />
</Stack.Navigator>
</NavigationContainer>
);
}
이때에는 매개변수를 다르게 전달한다
navigation.navigate('Account', {
screen: 'Settings',
params: { user: 'jane' },
});
navigate push 탐색 중인 경로에 매개 변수를 전달할 수 있도록 선택적 두 번째 인수를 수락합니다 . 예: navigation.navigate('RouteName', { paramName: 'value' })route.params화면 내부 를 통해 매개변수를 읽을 수 있습니다 .navigation.setParamsinitialParamsScreen 초기 매개변수는 소품을 통해 전달할 수 있습니다 .options ={}options={{ headerTitle: (props) => <LogoTitle {...props} /> }}function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
title: 'My home', // 타이틀
headerStyle: {
backgroundColor: '#f4511e', // 해더 배경색
},
headerTintColor: '#fff', // 해더 폰트컬러
headerTitleStyle: {
fontWeight: 'bold', // 폰트의 스타일 지정
},
}}
/>
</Stack.Navigator>
);
}
function StackScreen() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerTitle: (props) => <LogoTitle {...props} />, //커스텀 타이틀
headerRight: () => ( // 버튼 추가!
<Button
onPress={() => alert('This is a button!')}
title="Info"
color="#fff"
/>
),
}}
/>
</Stack.Navigator>
);
}
해당 화면에 초점이 맞춰져 있는 경우 콜백함수를 넣어 사용한다.
import { useFocusEffect } from '@react-navigation/native';
function Profile() {
useFocusEffect(
React.useCallback(() => {
// Do something when the screen is focused
return () => {
// Do something when the screen is unfocused
// Useful for cleanup functions
};
}, [])
);
return <ProfileContent />;
}
function Root() {
return (
<Drawer.Navigator>
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="Profile" component={Profile} />
<Stack.Screen name="Settings" component={Settings} />
// drawer 안에 stack이 중첩되어 있는 경우 stack의 헤더 위에 drawer이 나타난다.
</Drawer.Navigator>
);
}
function Home() {
return (
<Tab.Navigator>
<Tab.Screen name="Feed" component={Feed} />
<Tab.Screen
name="Chat"
component={Chat}
listeners={({ navigation, route }) => ({
tabPress: (e) => {
// Prevent default action
e.preventDefault();
// Do something with the `navigation` object
navigation.navigate('AnotherPlace');
//클릭 시 해당 페이지로 이동가능, 아래에 있던 탭이 사라지게 가능하다.
},
})}
/>
</Tab.Navigator>
);
}
<TouchableOpacity
accessible={true}
accessibilityLabel="Tap me!"
onPress={onPress}>
<View style={styles.button}>
<Text style={styles.buttonText}>Press me!</Text>
</View>
</TouchableOpacity>
이외에도 많은 것들이 있다.. https://reactnative.dev/docs/accessibility