我一直在尝试创建一个可触摸的亮点,该亮点通过使用this.props.navigation.navigate为我提供了一个新的场景。但是,React Native给我一个错误,认为未定义不是对象(评估'_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>
);
}
关于如何修复它的任何想法?
,尽管@justelouise是正确的,并且
stacknavigator definiton
代码的一部分将有所帮助,如果您使用堆栈导航器导航到此页面,则已经将其添加到Stick Navigator中。
我认为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>
)
}
}
如果您要导航到render()
之外的stackNavigator
,请尝试此
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')}
/>)
}
}