TypeError: undefined is not an object (evaluating this.props.navigation.navigate) in react native

TypeError: undefined is not an object (evaluating this.props.navigation.navigate) in react native

我刚刚开始使用 React Native。这是代码

app.js

import React, { Component } from 'react';

import { StackNavigator } from 'react-navigation';

import Splash from "./screens/splash";
import Home from "./screens/home";
import Card from "./screens/card";

export const RootNavigator = StackNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      header: null,
    },
  },
  Profile: {
    screen: Profile,
    navigationOptions: {
      headerTitle: 'Profile',
    },
  },
  Card: {
    screen: Card,
    navigationOptions: {
      header: null,
    },
  },
});

export default class App extends Component {

  constructor(props) {
    super(props);

    this.state = { showSplash: true };

    // after 1200ms change showSplash property for spalsh screen
    setTimeout(() => {
      this.setState(previousState => {
        return { showSplash: false };
      });
    }, 1200);
  }

  render() {
    if (this.state.showSplash) {
      return (<Splash />);
    } else {
      return (<RootNavigator />);
    }
  }
}

home.js中我是这样直接使用卡片组件的

<ScrollView>
{
  this.state.cards.map((data, index) => {
    return (
      <Card key={data.id} cardData={data} />
    );
  })
}

这里是 card.js

import React, { Component } from 'react';
import { Button, View, Text, Image } from 'react-native';

export default class Card extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        const { navigate } = this.props.navigation;
        return (
            <View>
                <View style={{ flex: 0.30 }}>
                    <Image source={{ uri: this.props.cardData.imgUrl }} style={{ height: 100 }} />
                </View>
                <View style={{ flex: 0.70, backgroundColor: 'steelblue' }}>
                    <Text >{this.props.cardData.name}</Text>
                    <Text >{this.props.cardData.imgUrl}</Text>
                    <Button
                        onPress={() => this.props.navigation.navigate('Profile', {})}
                        title="Profile"
                    />
                </View>
            </View>
        );
    }
}

现在如果我使用

const { navigate } = this.props.navigation;

profile.js 它有效,但在 card.js 的情况下它显示

TypeError : undefined is not an object (evaluating 'this.props.navigation.navigate')

这个问题被问了很多次并尝试了答案提供的所有解决方案,但 none 的答案有帮助。

这可能是什么问题?这是因为我在 Home 组件

中使用了 <Card>

如果我理解正确,home.js 屏幕中的 Card 组件是 card.js 中的组件。

因为您直接在 home.js 中使用 Card 组件(不是使用 react-navigation 导航到它),所以没有注入导航道具。如果你想让你当前的代码工作,你应该将导航道具从 profile.js

传递给你的卡片组件
const { navigation } = this.props;
...
<ScrollView>
{
  this.state.cards.map((data, index) => {
    return (
      <Card navigation={navigation} key={data.id} cardData={data} />
    );
  })
}
</ScrollView>

很可能,您正在使用 this.props.navigation.navigate('Profile') 打开 profile.js 屏幕,所以它在那里工作正常。