【发布时间】:2018-01-25 15:47:21
【问题描述】:
我刚刚开始使用 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')
这个问题被问了很多次,并尝试了答案提供的所有解决方案,但没有一个答案有帮助。
这可能是什么问题?这是因为我在Home 组件中使用了<Card>
【问题讨论】:
-
我没有看到你为 Card 组件设置
navigation属性。你是怎么定义profile的?
标签: android react-native react-native-android react-navigation