我一直在尝试通过使用this.props.navigation.navigate为一个本机应用程序创建一个可触摸的亮点,它带给我一个新的场景。但是,本机反应给了我一个错误,指出undefined不是一个对象(评估'_this2.props.navigation')。这是我的代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
ListView,
Image,
Text,
ScrollView,
TouchableHighlight
} from 'react-native';
import { DrawerNavigator } from 'react-navigation';
import { List, ListItem } from 'react-native-elements';
import beerlist from '../datbeerlist.json';
import BeerDetails from './BeerDetails';
const squadIcon = require('../../img/serioussquad.jpg');
class BeerList extends Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state = {
dataSource: ds.cloneWithRows(beerlist),
};
}
renderRow(beer) {
return (
<View style={styles.row}>
<Image style = {styles.icon} source = {squadIcon}/>
<View style={styles.info}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('BeerDetails')}>
<Text style={styles.items}>
{beer.name}
</Text>
</TouchableHighlight>
</View>
<View style={styles.total}>
<Text style={styles.price}>${(beer.price / 100).toFixed(2)}</Text>
</View>
</View>
);
}
有关如何修复它的任何想法?
答案 0 :(得分:1)
虽然@justelouise是对的
如果你使用堆栈导航器导航到这个页面,那么部分代码会有所帮助,那么它已经被添加到了棒状导航器中。StackNavigator Definiton
我认为this.props.navigation
方法下可以使用render()
。如果要在其他方法中使用它,则必须将其从render()
传递给所需的方法。像这样:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
ListView,
Image,
Text,
ScrollView,
TouchableHighlight
} from 'react-native';
import { DrawerNavigator } from 'react-navigation';
import { List, ListItem } from 'react-native-elements';
import beerlist from '../datbeerlist.json';
import BeerDetails from './BeerDetails';
const squadIcon = require('../../img/serioussquad.jpg');
class BeerList extends Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state = {
dataSource: ds.cloneWithRows(beerlist),
};
}
renderRow (beer, renderNavigation) {
return (
<View style={styles.row}>
<Image style={styles.icon} source={squadIcon}/>
<View style={styles.info}>
<TouchableHighlight onPress={() => renderNavigation.navigate('BeerDetails')}>
<Text style={styles.items}>
{beer.name}
</Text>
</TouchableHighlight>
</View>
<View style={styles.total}>
<Text style={styles.price}>${(beer.price / 100).toFixed(2)}</Text>
</View>
</View>
);
render () {
const navigation = this.props.navigation;
return (
<View>
{this.renderRow(BEER, navigation)}
</View>
)
}
}
答案 1 :(得分:0)
如果您要导航到stackNavigator
以外的render()
,请尝试
static navigationOptions = ({ navigation })=>{
const { navigate } = navigation
return{
title: 'Header Text',
headerRight:(<Button
title="Settings" backgroundColor="rgba(0,0,0,0)" color="rgba(0,122,255,1)"
onPress={() =>navigate('settings')}
/>)
}
}