react-native react-navigation 导航器的使用
1.基本使用
1.入口文件
import {AppStackNavigator} from './navigations/AppNavigation'
export default AppStackNavigator
2.配置文件
// AppNavigation.js
import React from 'react'
import {StackNavigator} from 'react-navigation'
import HomePage from '../pages/HomePage'
import Page1 from '../pages/Page1'
import Page2 from '../pages/Page2'
import Page3 from '../pages/Page3'
export const AppStackNavigator = StackNavigator({
HomePage: {
screen: HomePage
},
Page1: {
screen: Page1
},
Page2: {
screen: Page2
},
Page3: {
screen: Page3
}
})
3.目录
export default class HomePage extends Component {
render() {
const {navigation} = this.props
return (
<View style={styles.container}>
<Text style={styles.welcome}>
欢迎来到HomePage
</Text>
<Button
title='Go to Page1'
onPress={() => {
navigation.navigate('Page1')
}}
/>
<Button
title='Go to Page2'
onPress={() => {
navigation.navigate('Page2')
}}
/>
<Button
title='Go to Page3'
onPress={() => {
navigation.navigate('Page3')
}}
/>
</View>
);
}
}
2.配置navigationOptions的几种方式
2.1 全局静态配置
StackNavigator({
HomePage: {
screen: HomePage
},
Page1: {
screen: Page1
}
},{
navigationOptions: {
header: null
}
})
2.2 局部静态配置
StackNavigator({
HomePage: {
screen: HomePage,
navigationOptions: {
header: null
}
},
Page1: {
screen: Page1
}
})
2.3 静态配置-直接分配
export default class HomePage extends Component {
static navigationOptions = {
title: 'Home',
headerBackTitle: 'HaHa'
}
render() {
return (
<View style={styles.container}></View>
);
}
}
2.4 动态配置
export default class HomePage extends Component {
render() {
const {navigation} = this.props
return (
<View style={styles.container}>
<Text style={styles.welcome}>
欢迎来到HomePage
</Text>
<Button
title='Go to Page3'
onPress={() => {
navigation.navigate('Page3', {name: '动态的'})
}}
/>
</View>
);
}
}
// AppNavigation.js
StackNavigator({
HomePage: {
screen: HomePage
},
Page3: {
screen: Page3,
navigationOptions: ({navigation}) => ({
title: `${navigation.state.params.name}Page3`
})
}
})
3 setParams的使用,导航器与页面的通信
export default class Page4 extends Component {
render () {
const {navigation} = this.props
const {state, setParams} = navigation
const {params} = state
const showText = params.mode === 'edit' ? '正在编辑' : '编辑完成'
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Page4
</Text>
<Button
title='Go Back'
onPress={() => {
navigation.goBack()
}}
/>
<Text>{showText}</Text>
<TextInput style={styles.textInput}
onChangeText={text => {
setParams({
title: text
})
}}
/>
</View>
)
}
}
// AppNavigation.js
export const AppStackNavigator = StackNavigator({
HomePage: {
screen: HomePage
},
Page4: {
screen: Page4,
navigationOptions: (props) => {
const {navigation} = props
const {state, setParams} = navigation
const {params} = state
return {
title: params.title ? params.title : 'This is Page4',
headerRight: (
<Button
title={params.mode === 'edit' ? '保存' : '编辑'}
onPress={() => {
setParams({
mode: params.mode === 'edit' ? '' : 'edit'
})
}}
/>
)
}
}
}
})