代码之家  ›  专栏  ›  技术社区  ›  Anilkumar iOS Developer

如何在createStackNavigator中从navigationoptions传递和检索键值

  •  0
  • Anilkumar iOS Developer  · 技术社区  · 7 年前

    我们正试图通过navigationoptions传递stacknavigator的键值,但它是未定义的。

    我正在使用以下版本的react导航

    "react-navigation": "^3.0.9",
    
    const Stack = createStackNavigator(
      {
        Mobile: { screen: Mobile, navigationOptions: { header: null, Key: true } },
        Login: { screen: Login, navigationOptions: { header: null } },
        DB: { screen: DB, navigationOptions: { header: null } },
      },
      {
        initialRouteName: 'Mobile',
      },
    );
    

    但是,在尝试访问该键值时,会出现未定义的情况。

      componentDidMount() {
        const { navigation } = this.props;
        const key = JSON.stringify(navigation.getParam('key'));
    }
    

    有什么建议吗?

    0 回复  |  直到 7 年前
        1
  •  0
  •   timothyjoseph    7 年前

    使用 getParam ,你需要先 setParams 。您可以在创建密钥的组件中指定密钥 stack 变量

    在下面的示例中,我在同一个组件中使用了setParam。功能 getParam 被称为,打印 name 当你按下按钮时 TouchableOpacity Mobile 组成部分

    class Mobile extends Component {
      componentDidMount() {
        const { navigation } = this.props;
        navigation.setParams({ name: 'Lucy' });
      }
      render() {
        return (
          <View>
            <Text>Mobile</Text>
            <TouchableOpacity
              style={{backgroundColor: 'red', height: 200, width: 200}}
              onPress={() => console.log(this.props.navigation.getParam('name'))}
            />
          </View>
        );
      }
    }
    

    您可以参考 setParam 第节: https://reactnavigation.org/docs/en/navigation-prop.html

    推荐文章