我的反应本机代码:
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'
});
}
我想使用 onPress
功能导航到 DetailPage
。如果我像这样提醒它:
onPress(user){ Alert.alert(user.name)}
我确实得到了值,但是如何将它传递到其他页面?
非常感谢!
原文由 Somename 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
navigate
函数的第二个参数传递参数:反应导航 5.x、6.x (2022)
在
this.props.route.params
中访问它们。例如在您的DetailsPage
中:https://reactnavigation.org/docs/params/
反应导航 <= 4.x
在
this.props.navigation.state.params
中访问它们。例如在您的DetailsPage
中:https://reactnavigation.org/docs/4.x/params/