felix-cao / Blog

A little progress a day makes you a big success!
31 stars 4 forks source link

React Navigation 参数传递 #141

Open felix-cao opened 5 years ago

felix-cao commented 5 years ago

《React Navigation 的 Screen 切换及路由配置 》中,我们聊了 Screen 切换,同 WEBa 的页面跳转一样,都是可以带参数的。本篇来学习一下Screen 切换中的参数传递。需要掌握下面两个知识点:

一、传递参数

HomeScreen 中点击 Button 按钮时,传递给名字为 Details 的路由两个参数,itemIdotherParam

class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            /* 1. Navigate to the Details route with params */
            this.props.navigation.navigate('Details', {
              itemId: 86,
              otherParam: 'anything you want here',
            });
          }}
        />
      </View>
    );
  }
}

二、读取参数

DetailsScreen 中读取这两个参数, 并显示出来

class DetailsScreen extends React.Component {
  render() {
    /* 2. Get the param, provide a fallback value if not available */
    const { navigation } = this.props;
    const itemId = navigation.getParam('itemId', 'NO-ID');
    const otherParam = navigation.getParam('otherParam', 'some default value');
    // const otherParam = this.props.navigation.state.params.otherParam;

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Text>itemId: {JSON.stringify(itemId)}</Text>
        <Text>otherParam: {JSON.stringify(otherParam)}</Text>
        <Button
          title="Go to Details... again"
          onPress={() =>
            this.props.navigation.push('Details', {
              itemId: Math.floor(Math.random() * 100),
            })}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

snack 上跑一把