3.5 使用 withNavigation 跳转到搜索页

点击图3-10 中的搜索按钮,跳转到搜索页面。创建 src/pages/SearchPage.js ,为了适配 iPhoneX ,当前页面使用 SafeAreaView

代码如下:

import React, {Component} from 'react';
import {
    Text,
    StyleSheet, StatusBar
} from 'react-native';
import { SafeAreaView } from 'react-navigation';

type Props = {};
export default class SearchPage extends Component<Props> {

    render() {
        return ( // 渲染布局
            <SafeAreaView style={styles.container}>
                <StatusBar barStyle={'dark-content'} backgroundColor={'#fff'}/>
                <Text style={{margin:10,fontSize:20,color:'black'}}>搜索</Text>
            </SafeAreaView>
        );
    }
}
// 样式文件
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    }
});

SearchPage 需要加入到路由配置中,我们把他加入到 createStackNavigator 中,修改 App.js :

const App = createStackNavigator({
    SplashPage: {
        screen: SplashPage,
        navigationOptions: {
            gesturesEnabled: true,
            header: null  //去掉 react-navigation 提供的标题
        }
    },
    MyTab: {
        screen: MyTab,
        navigationOptions: {
            gesturesEnabled: true,
            header: null
        }
    },
    SearchPage: {
        screen: SearchPage,
        navigationOptions: {
            gesturesEnabled: true,
            header: null
        }
    }
}, {
    mode: 'card',// 页面切换模式, 左右是card(相当于iOS中的push效果), 上下是modal(相当于iOS中的modal效果)
    headerMode: 'none',//// 导航栏的显示模式, screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏
    transitionConfig: () => ({ //切换动画
        screenInterpolator: CardStackStyleInterpolator.forHorizontal //水平动画
    })
});

修改 CustomTabBar ,设置按钮的点击事件,跳转到搜索页 :

class CustomTabBar extends Component {
    render() {
        return (
            <View style={{position: 'relative', backgroundColor: '#fff'}}>
                <MaterialTopTabBar {...this.props}/>
                <TouchableOpacity style={{position: 'absolute', right: 12, bottom: 10}}
                                  onPress={() => this.props.navigation.navigate('SearchPage')}>
                    <Ionicons name={'ios-search-outline'}
                              size={22}
                              color={'#666666'}/>
                </TouchableOpacity>
            </View>
        );
    }

}

this.props.navigation.navigate('SearchPage') 这句代码用来跳转到搜索页,但是如果只是这样写的话程序会报错,因为 CustomTabBar 是一个普通组件,并没有直接添加到页面路由中,是不具备 navigation 属性的,如果需要获取 navigation 属性需要通过 withNavigation 包装下。修改 src/component/CustomTabBar.js

import {withNavigation} from 'react-navigation';
class CustomTabBar extends Component {
    // 代码不变

}
export default withNavigation(CustomTabBar); //导出时用 withNavigation 包装

引用react-navigation 提供的 withNavigation 组件,导出 CustomTabBar 时用 withNavigation 包装下,这时候就可以在 CustomTabBar 中石油 navigation 属性了。

查看代码

如果你已经从 GitHub 上克隆了这个程序的 Git 仓库,那么可以执行 git checkout 3f 签出程序的这个版本。

results matching ""

    No results matching ""