首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:未定义不是对象(计算“”_this3.state.bind“”)

TypeError:未定义不是对象(计算“”_this3.state.bind“”)
EN

Stack Overflow用户
提问于 2019-12-07 19:09:04
回答 1查看 490关注 0票数 1

App.js代码:

代码语言:javascript
复制
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原生的初学者,我不知道如何在不同的类中使用状态。一定要解释状态的概念以及解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-07 19:43:56

你必须把你的count作为道具发送给你的DetailsPage。因此,在代码中,它将如下所示:

代码语言:javascript
复制
<Button
       title="Go to Details"
       onPress={() => {
            this.incrementCount();
            this.props.navigation.navigate('Details',{count:this.state.count});           
       }}/>

在你的DetailsScreen中,你必须像这样访问它:

代码语言:javascript
复制
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>
    );
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59225357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档