Asks yourself a few more every day, always have an unexpected gain.A rookie Xiaobai’s growth (Copyer)
react-native official website’s main push plan is a separate navigation libraryreact-navigation
official website address
https://reactnavigation.org/
react-navigation has a lot of versions, and the version changes are still very large. I have just started to learn from the latest version of React-Native. The nearest version is the nearest version.6.x version
yarn add @react-navigation/native // Install the navigation library
yarn add react-native-screens react-native-safe-area-context // The dependency library of installing navigation
yarn add @react-navigation/native-stack // Install the stack route
yarn add @react-navigation/bottom-tabs // Install TAB route
yarn add @react-navigation/drawer // Install drawer route
Here we combine the official website and write while watching.
If you want to use the route in the project, you need
@react-navigation/native
provided a componentNavigationContainer
In the root of the projectindex.js
orapp.js
as a root component
error summary:
HereNavigationContainer
As a root component, there will be no phenomenon
// Wrong writing, the route here does not take effect here
<View>
<Text>Test project11</Text>
<NavigationContainer>
<Navigator initialRouteName="Home">
<Screen name="Home" component={
Home} />
<Screen name="About" component={
About} />
</Navigator>
</NavigationContainer>
</View>
// Correct writing
<NavigationContainer>
<Text>Test project11</Text>
<Navigator initialRouteName="Home">
<Screen name="Home" component={
Home} />
<Screen name="About" component={
About} />
</Navigator>
</NavigationContainer>
Use here
stack route
, you need to use it@react-navigation/native-stack
Export a functioncreateNativeStackNavigator
createNativeStackNavigator
is a function that returns an object, including two attributesScreen
andNavigator
. They are used to configure React-Navigation routing navigation.Navigator
Component should containScreen
components are used to define routing.
import React from 'react'
import {
View, Text, Button } from 'react-native'
import {
NavigationContainer } from '@react-navigation/native'
import {
createNativeStackNavigator } from '@react-navigation/native-stack'
const Home = () => {
return (
<View style={
{
flex: 1, backgroundColor: '#84bf96', justifyContent: 'center', alignItems: 'center'}}>
<Text>Home</Text>
</View>
)
}
// CreatenAdACKNAVIGATOR method
const Stack = createNativeStackNavigator()
// Objects returned from the structure
const {
Navigator, Screen} = Stack
const App = () => {
return (
<NavigationContainer>
// Including relationships
<Navigator>
// Routing configuration, name, and rendering components
<Screen name="Home" component={
Home} />
</Navigator>
</NavigationContainer>
)
}
export default App;
Effect chart:
Use
Screen
component, this component is a high -end component, which will enhanceprops
, in the component used, anavigation
objectIn this object, there is another
navigate
Properties are a function, which is used to jump pages.Screen
name
Value attributes (simply speaking, it is to jump the page with the name)Yellow area: In other words, if a Name is not defined, the entire program will report an error. In other ways, the acceptance value of Navigate is that we have defined
<NavigationContainer>
<Navigator initialRouteName="Home">
<Screen name="Home" component={
Home} />
<Screen name="About" component={
About} />
</Navigator>
</NavigationContainer>
Here registeredHome
andAbout
Two name value, just givenavigate
const Home = (props) => {
// Get Navigation object in PROPS
const {
navigation } = props
return (
<View style={
{
flex: 1}}>
<Text>Home</Text>
// Use the Navigate function to restrain the name value, and then jump the page to jump
<Button onPress={
() => navigation.navigate('About')} title="Jump"/>
</View>
)
}
Other ways jump routing
The first paragraph, in simple terms, is Navigate accept
The same parameters, will not jump
。
navigate('about')
The first execution, it will turn around the About page
navigate('about')
The second execution, if it is currently on the About page, the Navigate function will not be processed.Section 2: It is the same page that we just want to stop (rendering, according to the parameters passed by, rendering different effects, but they are all the same components)
So I recommend here
The method of
push
, using the push method, a new navigation is added to the navigation stack every time
<Button
title="Go About"
onPress={
() => navigation.push('About')}
/>
Back jumping method
goBack()
: Back to the previous level
popToTop
: Return to the top of the stack (the first -rended page)
<Button
title="Return"
onPress={
() => navigation.goBack()}
/>
<Button
title="Return to the Home"
onPress={
() => navigation.popToTop()}
/>
Route passing parameters,
navigate
Accept the second parameter, the image of the object, pass the parametercomponent accepts parameters of routing transmission,
route
tooScreen
PROPS enhanced,Route is also an object
, contains a attributeparams
, it is used to accept the parameters passed over
// Home Components: Transmit parameters
const Home = (props) => {
const {
navigation } = props
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>Home</Text>
// Pass parameter
<Button onPress={
() => navigation.navigate('About', {
name: 'copyer'})} title="Jump"/>
</View>
)
}
// About component: accept parameters
const About = (props) => {
const {
params } = props.route
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>About</Text>
<Text>Accepted routing parameters:{
params.name}</Text>
</View>
)
}
Effect chart:
Other points
Component can be new with
params
, like the new internal state, usesetParams()
const About = ({
route, navigation}) => {
const {
params } = route
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text>About</Text>
<Text>Accepting routing parameters:{
params.name}</Text>
// and New Params
<Button title="Following New" onPress={
() => navigation.setParams({
name: 'james'
})}></Button>
</View>
)
}
initialization
params
, if there is no specified specialparams
will achieve initialization value, and the object of initialization will also be combined with shallow layers. The attributes usedinitialParams
// The default value of initialization
<Screen name="About" component={
About} initialParams={
{
name: 'kobe'}} />
// Pass parameter
navigation.navigate('About', {
name: 'james'})The value passed here "" "" "" "" higher than the values of initialization (displayed the transmitted value)
// The default value of initialization
<Screen name="About" component={
About} initialParams={
{
name: 'kobe'}} />
// Pass parameter
navigation.navigate('About', {
age: '12'})Here will be a shallow merger
route.params = {
name: 'kobe',
age: '12'
}
Here is the main thing: when the routing parameters, it should be the minimized data, not passing the complete data, which will cause accidental errors. (The data is not synchronized, and some places are modified, which cannot be reflected in the routing.) The data of each page is best to obtain detailed data through the unique value.
Screen
component acceptanceoptions
as a props,
options
can be an object, or a function, return a object
<Stack.Screen
name="About"
component={
About}
options={
({
route }) => ({
title: route.params.name })}
/>
Here Options is a function, accepting parameters, the same as the enhancement in props, allnavigation
androute
Update
options
, usesetOptions
Set some configuration attributes of the style at the top
headerStyle
: For the style of the top box
headerTintColor
:Return button
andtitle
All use this color
haederTitleStyle
: Solocenttitle
style settings
<Screen name="Home"
component={
Home}
options={
{
headerStyle:{
backgroundColor: 'yellow'},
headerTintColor: 'red',
headerTitleAlign: 'center',
headerTitleStyle: {
fontWeight: 'bold'
}
}} />
Use the same style for multiple routes, you can write it in
navigator
component
<Navigator
screenOptions={
{
headerStyle:{
backgroundColor: 'yellow'},
headerTintColor: 'red',
headerTitleAlign: 'center',
headerTitleStyle: {
fontWeight: 'bold'
}
}}
>
<Screen
name="Home"
component={
Home}
options={
{
title: 'My home' }}
/>
<Screen
name="About"
component={
About}
options={
{
title: 'About' }}
/>
</Navigator>
Other configuration:
headerTitle
: Set Title as a rendering component
headerRight
: Set the component on the top and right of the top
headerLeft
: Set the component on the left side of the top
function Home() {
return (
<Tab.Navigator>
<Tab.Screen name="Feed" component={
Feed} />
<Tab.Screen name="Messages" component={
Messages} />
</Tab.Navigator>
);
}
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={
Home}
options={
{
headerShown: false }}
/>
<Stack.Screen name="Profile" component={
Profile} />
<Stack.Screen name="Settings" component={
Settings} />
</Stack.Navigator>
</NavigationContainer>
);
}
The structure of the embedded routing
Use
navigate
Method jump,A
jump to turn toB
, then componentscomponentDidMount
will be executed, usedgoBack()
Return
componentWillUnmount
will also be executed.Of course, the life cycle of the web side is used for
react-navigatioin
, there must be different things.
Consider one situation and enter
a page
,componentDidMount
Executive, shouldA->B
Time (usepush()
method),B
componentDidMount
was executed, butThe
A
page is unanimously mounted, socomponentWillUnmount
will not be executed.
b Return to A
At, B
componentWillUnmount
is executed, but AcomponentDidMount
is not executed, because A’s page is always in a state of mounting.
function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="First">
{
() => (
<SettingsStack.Navigator>
<SettingsStack.Screen
name="Settings"
component={
SettingsScreen}
/>
<SettingsStack.Screen name="Profile" component={
ProfileScreen} />
</SettingsStack.Navigator>
)}
</Tab.Screen>
<Tab.Screen name="Second">
{
() => (
<HomeStack.Navigator>
<HomeStack.Screen name="Home" component={
HomeScreen} />
<HomeStack.Screen name="Details" component={
DetailsScreen} />
</HomeStack.Navigator>
)}
</Tab.Screen>
</Tab.Navigator>
</NavigationContainer>
);
}
Four routes will be stored after being loaded.
The current goal is: I want to know which component is in an active state, and then do something alone
1, monitorfocus
event
function Profile({
navigation }) {
React.useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
// Screen was focused
// Do something
});
return unsubscribe;
}, [navigation]);
return <ProfileContent />;
}
2. Use the hook function
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 />;
}
import * as React from 'react';
import {
Button, Text, View } from 'react-native';
import {
NavigationContainer } from '@react-navigation/native';
import {
createNativeStackNavigator } from '@react-navigation/native-stack';
import {
createBottomTabNavigator } from '@react-navigation/bottom-tabs';
function DetailsScreen() {
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Details!</Text>
</View>
);
}
function HomeScreen({
navigation }) {
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home screen</Text>
<Button
title="Go to Details"
onPress={
() => navigation.navigate('Details')}
/>
</View>
);
}
function SettingsScreen({
navigation }) {
return (
<View style={
{
flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Settings screen</Text>
<Button
title="Go to Details"
onPress={
() => navigation.navigate('Details')}
/>
</View>
);
}
const HomeStack = createNativeStackNavigator();
function HomeStackScreen() {
return (
<HomeStack.Navigator>
<HomeStack.Screen name="Home" component={
HomeScreen} />
<HomeStack.Screen name="Details" component={
DetailsScreen} />
</HomeStack.Navigator>
);
}
const SettingsStack = createNativeStackNavigator();
function SettingsStackScreen() {
return (
<SettingsStack.Navigator>
<SettingsStack.Screen name="Settings" component={
SettingsScreen} />
<SettingsStack.Screen name="Details" component={
DetailsScreen} />
</SettingsStack.Navigator>
);
}
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator>
<Tab.Screen name="Home" component={
HomeStackScreen} />
<Tab.Screen name="Settings" component={
SettingsStackScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
<Tab.Navigator
screenOptions={
({
route }) => ({
tabBarIcon: ({
focused, color, size }) => {
let iconName;
if (route.name === 'Home') {
iconName = focused
? 'ios-information-circle'
: 'ios-information-circle-outline';
} else if (route.name === 'Settings') {
iconName = focused ? 'ios-list-box' : 'ios-list';
}
// You can return any component that you like here!
return <Ionicons name={
iconName} size={
size} color={
color} />;
},
tabBarActiveTintColor: 'tomato',
tabBarInactiveTintColor: 'gray',
})}
>
</Tab.Navigation>
import * as React from 'react';
import {
Button, View } from 'react-native';
import {
createDrawerNavigator } from '@react-navigation/drawer';
import {
NavigationContainer } from '@react-navigation/native';
function HomeScreen({
navigation }) {
return (
<View style={
{
flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
onPress={
() => navigation.navigate('Notifications')}
title="Go to notifications"
/>
</View>
);
}
function NotificationsScreen({
navigation }) {
return (
<View style={
{
flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button onPress={
() => navigation.goBack()} title="Go back home" />
</View>
);
}
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={
HomeScreen} />
<Drawer.Screen name="Notifications" component={
NotificationsScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
Plaid for one afternoon, yesreact-navigation
has a general understanding. In the development process, I feel that the code can still be understood. Instead of learning, only you are slowly enriched.