頭部按鈕
- 通過headerLeft和headerRight來添加左右按鈕
class HomeScreen extends React.Component {
static navigationOptions = ({navigation})=>{
return {
// title: 'Home',
headerTitle:<LogoTitle/>,
// 同時(shí)添加左右鍵 保證居中
headerLeft:(
<Button onPress={()=>navigation.goBack()}
title ="Back"
color = "#000" />
),
// 添加一個(gè)右鍵
headerRight:(
<Button onPress={()=> alert('just test')}
title ="info"
color = "#839"
/>
),
......下略
在navigationOptions,this指向的不是HomeScreen幸撕,所以不能用this來調(diào)用。
用自定義的按鈕連接goBack方法援所,可以處理默認(rèn)返回鍵返回很慢的問題外莲。
- js中的 || 運(yùn)算
前面看到一個(gè)獲取參數(shù)的例子是這樣的
// 函數(shù)傳入一個(gè)navigation,獲取state降铸,設(shè)置title
static navigationOptions = ({navigation,navigationOptions}) =>{
const {params} = navigation.state;
return {
title:params?params.msg:'A Details Screen',
}
};
在將頭部按鈕時(shí)在旱,官方又給了一個(gè)這樣的例子
const params = navigation.state.params || {};
查了下,js中表示垮耳,navigation.state.params不為空則賦值颈渊,否則使用后面的值賦值。和java的短路或不太一樣终佛。
RN不能保證你的screen組件的掛載會(huì)優(yōu)先于你的header俊嗽,所以params可能為{};
可以通過Redux或者M(jìn)obx來實(shí)現(xiàn)header和screen的交互
- 自定義返回按鈕
headerBackTitle IOS 有效
headerTruncatedBackTitle 似乎安卓無效
headerBackImage 注意背景色不要覆蓋,否則只能看到色塊 铃彰。
通過設(shè)置headerLeft可以覆蓋默認(rèn)返回按鈕
Opening a full-screen modal(全屏模態(tài)展示)
modal
A modal displays content that temporarily blocks interactions with the main view(臨時(shí)地阻止與主屏幕的交互绍豁,這種展示形式成為模態(tài)展示)建立一個(gè)模態(tài)頁面
class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const params = navigation.state.params || {};
return {
headerLeft: (
<Button
onPress={() => navigation.navigate('MyModal')}
title="Info"
color="#fff"
/>
),
/* the rest of this config is unchanged */
};
};
/* render function, etc */
}
class ModalScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 30 }}>This is a modal!</Text>
<Button
onPress={() => this.props.navigation.goBack()}
title="Dismiss"
/>
</View>
);
}
}
const MainStack = StackNavigator(
{
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
},
{
/* Same configuration as before */
}
);
const RootStack = StackNavigator(
{
Main: {
screen: MainStack,// 這個(gè)有導(dǎo)航欄
},
MyModal: {
screen: ModalScreen, // 這個(gè)沒有導(dǎo)航欄
},
},
{
mode: 'modal',
headerMode: 'none',// 設(shè)置模式 不加Main會(huì)有兩個(gè)導(dǎo)航欄
}
);
這里實(shí)現(xiàn)了兩個(gè)StackNavigator的嵌套,一個(gè)棧是有導(dǎo)航欄的牙捉,一個(gè)棧是沒有的竹揍。
模式配置可以是card或者modal敬飒,這個(gè)對(duì)安卓沒有影響,只影響ios上的轉(zhuǎn)換效果(modal時(shí)從下到上芬位,card是從右到左)
在導(dǎo)航時(shí)不需要指定所在的棧无拗,只需要指定頁面名稱。官方提供了這樣一張圖昧碉。從HOME導(dǎo)航到modal英染,如果mainstack不能處理,會(huì)交給rootstack來處理被饿。
tree.png
其他
- StackNavigator不能實(shí)現(xiàn)圖表式的切換四康,需要使用TabNavigator。這里先不提狭握,參見TabNavigator
- 想要了解內(nèi)部機(jī)理參見Build your own Navigator
- 其他API參見API Reference