react native 使用react-navigation
react native使用react-navigation跳转页面
·
官网连接
https://reactnavigation.org/docs/getting-started/
1.安装
安装的时候,需要安装多个。按照官方文档,依次输入命令行。
也可以直接输入下面命令行一步完成。
yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view @react-navigation/stack @react-navigation/native
2.使用
(1)我自己建了route.js
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import * as React from "react";
//引入页面js
import Login from "../pages/login";
import Mine from "../pages/mine";
import EditSelf from '../pages/editSelf';
import Land from "../pages/land";
import Draw from "../pages/draw";
import AddLand from "../pages/addland";
//
import Tarbar from "../tabbar/tarbar";
const Stack = createStackNavigator();
export default () => {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{headerShown:false}}
options={{ title: 'My home' }} initialRouteName="Login">
<Stack.Screen name="Home" component={Login} />
<Stack.Screen name="Tarbar" component={Tarbar} />
<Stack.Screen name="Mine" component={Mine} />
<Stack.Screen name="EditSelf" component={EditSelf} />
<Stack.Screen name="Land" component={Land} />
<Stack.Screen name="Draw" component={Draw} />
<Stack.Screen name="AddLand" component={AddLand} />
</Stack.Navigator>
</NavigationContainer>
)
}
注意:
screenOptions={{headerShown:false}}
引入的每个页面都有头部导航栏,这个隐藏头部导航
name 是后续调转页面用的,component 使用哪个页面
<Stack.Screen name=“Home” component={Login} />
(2)在app.js 引入
import * as React from 'react';
//引入导航
import Nav from './src/route/index'; // 自定义导航js
// 引入全局变量
import "./src/comm/global";
function App() {
return (
// 使用自定义导航
<Nav></Nav>
);
}
export default App;
- 调转页面
调转页面需要先从props获取navigation
类组件
/*
登录页
* */
class Index extends React.Component {
// 1 声明state
state = {
num: 100,
phone:'',
password:''
};
render() {
return (
<View>
<TouchableOpacity style={styles.btn} activeOpacity={0.5} onPress={this.handlePress}><Text
style={styles.btnText} >登陆</Text></TouchableOpacity>
</View>
);
}
// 3 修改state
handlePress = () => {
this.setState({ num: 10 });
this.props.navigation.replace("Tarbar");
};
onChangeTextHandle=(value)=>{
this.setState({phone: value});
}
}
export default Index;
函数组件
const Index=(props)=>{
const press=()=>{
props.navigation.navigate('Draw')
}
return (
<TouchableOpacity style={styles.btn} onPress={press}>
<Text style={styles.btn_text}>确定</Text>
</TouchableOpacity>
</View>
)
}
export default Index;
常用方法
navigation.navigate(‘name’) // 新页面进栈 保留原页面
navigation.replace(‘name’) // 替换原页面
navigation.goBack() // 返回
更多推荐
已为社区贡献3条内容
所有评论(0)