我试图在我的应用程序的屏幕之间传递数据。目前我正在使用
"react-native": "0.46.0", "react-navigation": "^1.0.0-beta.11"
我有我的index.js
import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import App from './src/App' import { StackNavigator } from 'react-navigation'; import SecondScreen from './src/SecondScreen' class med extends Component { static navigationOptions = { title: 'Home Screen', }; render(){ const { navigation } = this.props; return ( <App navigation={ navigation }/> ); } } const SimpleApp = StackNavigator({ Home: { screen: med }, SecondScreen: { screen: SecondScreen, title: 'ss' }, }); AppRegistry.registerComponent('med', () => SimpleApp);
应用为
import React, { Component } from 'react'; import { StyleSheet, Text, Button, View } from 'react-native'; import { StackNavigator } from 'react-navigation'; const App = (props) => { const { navigate } = props.navigation; return ( <View> <Text> Welcome to React Native Navigation Sample! </Text> <Button onPress={() => navigate('SecondScreen', { user: 'Lucy' })} title="Go to Second Screen" /> </View> ); } export default App
然后在secondscreen.js中,我们将从前一个屏幕获取的数据作为
import React, { Component } from 'react'; import { StyleSheet, Text, View, Button } from 'react-native'; import { StackNavigator } from 'react-navigation'; const SecondScreen = (props) => { const { state} = props.navigation; console.log("PROPS" + state.params); return ( <View> <Text> HI </Text> </View> ); } SecondScreen.navigationOptions = { title: 'Second Screen Title', }; export default SecondScreen
每当我console.log我得到未定义。 https://reactnavigation.org/docs/navigators/navigation- prop 文档说每个屏幕都应该具有这些值,我在做什么错呢?
在您的代码中,props.navigation和this.props.navigation.state是两件事。您应该在第二个屏幕中尝试以下操作:
const {state} = props.navigation; console.log("PROPS " + state.params.user);
该const {state}行仅在这里得到易于阅读的代码。
const {state}