首页 > 解决方案 > 将本机传递数据反应到另一个屏幕

问题描述

我需要将数据传递到另一个屏幕。这是导航堆栈中的代码

 <Stack.Screen name="MyScreen" component={MyScreen} options={({ route }) => ({ title: 'Profile', url: 'http://www.google.com' })} />

在另一个屏幕上,这是我的代码,但我看不到参数。

import { Alert, View, Text, StyleSheet,} from 'react-native';

export default class MyScreen extends Component {

    render() {
        const { navigation } = this.props;
        let mydata = navigation.getParam('url', 'http://');
        alert(mydata);


    }
}

标签: react-nativeparameter-passingreact-navigationreact-navigation-v5

解决方案


在反应导航 v5

你可以像这样设置initialParams

<Stack.Screen
  name = "MyScreen"
  component = {MyScreen}
  initialParams = {{
    myParam: 'Example value from param',
    myAnotherParam: 5
  }}
/>

然后在屏幕的脚本中,您可以像这样访问 myParam 或 myAnotherParam

this.props.route.params.myParam // 'Example value from param'

this.props.route.params.myAnotherParam // 5

推荐阅读