将参数传递到后屏并在 React Native 中设置状态



我试图将参数数据从第二个屏幕传递到第一个屏幕,但没有得到。 我是新来的 反应原生.也在谷歌上搜索,但由于反应本机版本更改代码无法正常工作。

这是第一个屏幕代码

import React, { Component } from "react";
import { Button, Text, View } from "react-native";
export default class viewA extends Component {
constructor(props){
super(props);
}
state = { selected: 'hiii' };
onSelect = (data) =>{
this.setState(data)
}
onPress = () => {
this.props.navigation.navigate("viewB",{ onSelect: this.onSelect })
}
render() {
return (
<View style={{marginTop:100}}>
<Text>{this.state.selected}</Text>
<Button title="Next" onPress={this.onPress} />
<Text>{JSON.stringify(this.props)}</Text>
</View>
);
}
}

第二屏代码-

import React, { Component } from "react";
import { Button, Text, View,Alert } from "react-native";
export default class viewB extends Component {
constructor(props){
super(props);
}
goBack= ()=> {
this.props.navigation.goBack();
this.props.navigation.state.params.onSelect({ 'selected':'hello'});
}
render() {
return (
<View style={{marginTop:100}}>
<Button title="back" onPress={this.goBack} />
<Text>{JSON.stringify(this.props)}</Text>
</View>
)
}
}

这是我的反应原生博览会链接的链接,可以编辑代码

https://snack.expo.io/@vikraant/param-to-back-page

谢谢

这就是我将数据传递到另一个屏幕的方式,请参阅下面的代码和博览会小吃链接:

import React from 'react';
import { Button, View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Text>{this.props.navigation.getParam('itemId','No data passed')}</Text>
<Button
title="Go to Details"
onPress={() => {
this.props.navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
render() {
const { navigation } = this.props;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>
itemId: {JSON.stringify(navigation.getParam('itemId', 'NO-ID'))}
</Text>
<Text>
otherParam:{' '}
{JSON.stringify(navigation.getParam('otherParam', 'default value'))}
</Text>
<Button
title="Go to Details... again"
onPress={() =>
navigation.push('Home', {
itemId: 'hello',
})
}
/>
</View>
);
}
}

const RootStack = createStackNavigator({
Home: HomeScreen,
Details: DetailsScreen,
});
export default createAppContainer(RootStack);

展会链接 : 展会 - 链接

这里 HOmepage 是第一个屏幕,细节是第二个屏幕。我将 itemId 从详细信息再次传递到主页,并打招呼,我在主屏幕中呈现为<Text>{this.props.navigation.getParam('itemId','No data passed')}</Text>

希望它有助于 .随意怀疑。