App.js代码:
import React from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
constructor(props){
super(props);
this.state={count:0};
this.incrementCount=this.incrementCount.bind(this)
}
incrementCount(){
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.homeScreen}>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details');
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
constructor(props){
super(props);
this.state=this.state.bind(this)
this.incrementCount=this.incrementCount.bind(this)
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Hello </Text>
</View>
);
}
}
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);
const styles= StyleSheet.create({
homeScreen:{
}
});
export default createAppContainer(AppNavigator);我想在每次用户转到详细信息(第二页)页面时递增一个数字(0)。递增后的数字应显示在详细信息(第二页)页面上。
我是react原生的初学者,我不知道如何在不同的类中使用状态。一定要解释状态的概念以及解决方案。
发布于 2019-12-07 19:43:56
你必须把你的count作为道具发送给你的DetailsPage。因此,在代码中,它将如下所示:
<Button
title="Go to Details"
onPress={() => {
this.incrementCount();
this.props.navigation.navigate('Details',{count:this.state.count});
}}/>在你的DetailsScreen中,你必须像这样访问它:
class DetailsScreen extends React.Component {
constructor(props){
super(props);
//Remove these lines this is causing error and this is wrong
//this.state=this.state.bind(this)
//this.incrementCount=this.incrementCount.bind(this)
}
render() {
let count = this.props.navigation.getParam('count')
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>You were here {count} times </Text>
</View>
);
}
}https://stackoverflow.com/questions/59225357
复制相似问题