Mon React code natif:
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)}
/>
)
}
}
Configuration de navigation:
const NavigationTest = StackNavigator({
Home: { screen: HomeScreen },
DetailsPage: { screen: DetailsPage },
});
Les écrans de détails sont:
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>
);
}
}
Je ne peux pas passer le user
au DetailsPage
avec le code:
onPress(user){
this.props.navigator.Push({
id: 'DetailPage'
});
}
Je veux naviguer vers le DetailPage
avec la fonction onPress
. Si je l'alerte comme:
onPress(user){ Alert.alert(user.name)}
Je reçois la valeur, mais comment puis-je la transmettre à l'autre page?
Merci beaucoup!
Vous pouvez passer des paramètres avec le second argument de la fonction navigate
:
onPress(user) {
this.props.navigation.navigate(
'DetailPage',
{ user },
);
}
Et puis y accéder dans this.props.navigation.state.params
. Par exemple, dans votre DetailsPage
:
<Text style={styles.myStyle}>{this.props.navigation.state.params.user.name}</Text>
Référence: https://reactnavigation.org/docs/params.html