3.6 页面之间传递参数

现在我们已经知道了如何使用一些路由创建一个堆栈导航器,并在这些路由之间导航,现在让我们看看如何在导航它们时将数据传递给路由。

分为两步:

  1. 通过将传递的参数放在一个对象中,作为 navigation.navigate 的第二个参数。

    this.props.navigation.navigate('RouteName',{/* params到这里*/})
    
  2. 在跳转的页面通过 navigation.getParam 可以把值读出来。

    this.props.navigation.getParam(paramName, defaultValue).
    

以跳转到搜索页演示,修改 /src/component/CustomTabBar.js

//...
<TouchableOpacity style={{position: 'absolute', right: 12, bottom: 10}}
                  onPress={() => this.props.navigation.navigate('SearchPage', {
                                         param1: 86,
                                         param2: 'anything you want here'
                           )}>
     <Ionicons name={'ios-search-outline'}
               size={22}
               color={'#666666'}/>
</TouchableOpacity>

//...

传递了 param1 param2 两个参数,对应的值为 86 和一串字符串。搜索页可以接收到这俩参数。

type Props = {};
export default class SearchPage extends Component<Props> {
    render() {
        const {navigation} = this.props;
        const param1 = navigation.getParam('param1'); // 获取第一个参数
        const param2 = navigation.getParam('param2', 'some default value'); //获取第二个参数

        return ( // 渲染布局
            <SafeAreaView style={styles.container}>
                <StatusBar barStyle={'dark-content'} backgroundColor={'#fff'}/>
                <Text style={{margin: 10, fontSize: 20, color: 'black'}}>搜索{param1}{param2}</Text>
            </SafeAreaView>
        );
    }
}

getParam 第二个参数是参数的默认值,可以不设置。

查看代码

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

results matching ""

    No results matching ""