我的React Native代码:
import React, { Component } from 'react';
import { AppRegistry, ActivityIndicator, StyleSheet, ListView,
Text, Button, TouchableHighlight, View } from 'react-native';
import { StackNavigator } from 'react-navigation';
import DetailsPage from './src/screens/DetailsPage';
class HomeScreen extends React.Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
userDataSource: ds,
};
}
componentDidMount(){
this.fetchUsers();
}
fetchUsers(){
fetch('https://jsonplaceholder.typicode.com/users')
.then((response) => response.json())
.then((response) => {
this.setState({
userDataSource: this.state.userDataSource.cloneWithRows(response)
});
});
}
onPress(user){
this.props.navigator.push({
id: 'DetailPage'
});
}
renderRow(user, sectionID, rowID, highlightRow){
return(
<TouchableHighlight onPress={()=>{this.onPress(user)} } >
<View style={styles.row}>
<Text style={styles.rowText}> {user.name} </Text>
</View>
</TouchableHighlight>
)
}
render(){
return(
<ListView
dataSource = {this.state.userDataSource}
renderRow = {this.renderRow.bind(this)}
/>
)
}
}
导航配置:
const NavigationTest = StackNavigator({
Home: { screen: HomeScreen },
DetailsPage: { screen: DetailsPage },
});
详细信息屏幕是:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import styles from '../styles';
export default class DetailsPage extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: `User: ${navigation.state.params.user.name}`,
});
render() {
const { params } = this.props.navigation.state;
return (
<View>
<Text style={styles.myStyle}>Name: {params.name}</Text>
<Text style={styles.myStyle}>Email: {params.email}</Text>
</View>
);
}
}
我无法通过代码将user
传递给DetailsPage
:
onPress(user){
this.props.navigator.push({
id: 'DetailPage'
});
}
我想用DetailPage
函数导航到onPress
。如果我提醒它:
onPress(user){ Alert.alert(user.name)}
我确实得到了价值,但是如何将其传递给其他页面?
非常感谢!
你可以使用navigate
函数的第二个参数传递params:
onPress(user) {
this.props.navigation.navigate(
'DetailPage',
{ user },
);
}
然后在this.props.navigation.state.params
访问它们。例如在你的DetailsPage
中:
<Text style={styles.myStyle}>{this.props.navigation.state.params.user.name}</Text>
您可以使用react-navigation-helper
轻松获取参数:
例:
import { StackNavigator } from 'react-navigation';
import { StackNavigatorHelper } from 'react-navigation-helper';
import { Scene1, Scene2 } from './src';
export default StackNavigatorHelper.exportStackNavigator(
StackNavigator(
{
Scene1: { screen: StackNavigatorHelper.setInitParamsToProps(Scene1) },
Scene2: { screen: StackNavigatorHelper.paramsToProps(Scene2) }
}
)
);
并获取参数:
const parameterName = this.props.parameterName