首页 > 解决方案 > 如何在其他类中使用反应导航?

问题描述

我有一个标题和一个购物车按钮。此按钮用于导航到购物车屏幕。当我按下按钮时,我看到了错误。

错误:未定义不是对象(评估“_this3.props.navigation.navigate”)

标头在标头文件中的标头类中: 我在其他屏幕(例如钱包屏幕)中使用标头。

<Header style={styles.headerStyle}>
      <Body>
        <Text>Logo</Text>
      </Body>
      <Right>
      <TouchableOpacity activeOpacity={0.5} onPress={() => {
                      this.props.navigation.dispatch(StackActions.reset({
                        index: 0,
                        actions: [
                          NavigationActions.navigate({ routeName: 'Cart' 
      })
                        ],
                      }))
                    }}>
        <Icon type="MaterialCommunityIcons" name="washing-machine"/>
        {this.state.cartCountNumber != 0 ?(
            <View style={styles.cartCountBox}>
              <Text>{this.state.cartCountNumber}</Text>
            </View>
         ):null}
      </TouchableOpacity>
      </Right>
</Header>

钱包屏幕:当我在钱包内容中使用 on-press 时!

export default class WalletScreen extends React.Component{


render() {
  return (
    <Container>
    <HeaderShow />  // My header is here !!!!!!!!!!!!!!!!!!
    <Content>
    <Text>Wallet Screen</Text>



    // When I use button and on-press here, working fine!



    </Content>
   </Container>
   );
  }

 }

标签: react-native

解决方案


如果您在 Wallet 界面访问 this.props.navigation,当您在 Wallet 界面中将导航道具添加到 Header 时,它将起作用;

export default class WalletScreen extends React.Component {
    render() {
        return (
            <Container>
                <HeaderShow navigation={this.props.navigation}/> // My header is here !!!!!!!!!!!!!!!!!!
                <Content>
                    <Text>Wallet Screen</Text>


                    // When I use button and on-press here, working fine!


                </Content>
            </Container>
        );
    }
}

推荐阅读