gpt4 book ai didi

react-native - 如何在 StackNavigator 中将参数传递给屏幕?

转载 作者:行者123 更新时间:2023-12-03 09:45:05 25 4
gpt4 key购买 nike

我的 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>
);
}
}

我无法通过 userDetailsPage使用代码:
onPress(user){
this.props.navigator.push({
id: 'DetailPage'
});
}

我想导航到 DetailPageonPress功能。如果我提醒它:
onPress(user){ Alert.alert(user.name)}

我确实得到了值,但是如何将其传递到另一个页面?

非常感谢!

最佳答案

您可以使用 navigate 传递参数函数的第二个参数:

onPress(user) {
this.props.navigation.navigate(
'DetailPage',
{ user },
);
}

react 导航 5.x (2020)

this.props.route.params 中访问它们.例如在您的 DetailsPage :
<Text style={styles.myStyle}>{this.props.route.params.user.name}</Text>

https://reactnavigation.org/docs/params/

react 导航 <= 4.x

this.props.navigation.state.params 中访问它们.例如在您的 DetailsPage :
<Text style={styles.myStyle}>{this.props.navigation.state.params.user.name}</Text>

https://reactnavigation.org/docs/4.x/params/

关于react-native - 如何在 StackNavigator 中将参数传递给屏幕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45388957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com