我正在制作一个神奇宝贝,从FlatList
开始,我希望用户能够单击一个神奇宝贝,并直接进入该神奇宝贝的详细信息页面。但是,navigation.navigate在基于类和函数的视图中均不起作用。我看了看文档,它使用了我尝试实现的方法。怎么了?
App.js
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import PokedexData from './components/PokedexData';
import PokemonView from './components/PokedexData';
const Stack = createStackNavigator();
export default class App extends React.Component {
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
options={{headerShown: false}}
name="PokedexList"
component={PokedexData}
/>
<Stack.Screen name="PokemonView" component={PokemonView} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
PokedexData.js
import React, {Component} from 'react';
import axios from 'axios';
import {View, FlatList} from 'react-native';
import PodexRow from './PokedexRow';
export default class PokedexRow extends Component {
constructor(props) {
super(props);
this.state = {
pokemon: [],
};
}
componentDidMount() {
this.loadPokemon();
}
loadPokemon = () => {
axios
.get('https://pokeapi.co/api/v2/pokemon?limit=151')
.then((res) => this.setState({pokemon: res.data.results}));
};
renderItem = ({item}) => <PodexRow name={item.name} />;
render() {
return (
<FlatList
data={this.state.pokemon}
renderItem={this.renderItem}
keyExtractor={(item) => item.url}
/>
);
}
}
PokedexRow.js
import {View, StyleSheet, Text, Pressable} from 'react-native';
export default class PokedexRow extends Component {
constructor(props) {
super(props);
}
onPressHandle = () => {
alert(this.props.name);
const {navigate} = this.props.navigation;
};
render() {
return (
<View style={styles.PokedexRowView}>
<Pressable
style={styles.PokedexClickable}
onPress={this.onPressHandle}
android_ripple={{color: 'gray'}}>
<Text style={styles.PokedexRowText}>{this.props.name}</Text>
</Pressable>
</View>
);
}
}
const styles = StyleSheet.create({
/*stles removed for brevity*/
});
答案 0 :(得分:1)
因为PokedexRow不是您自动获得导航道具的屏幕。您可以将useNavigation用于功能组件来访问导航对象或将导航从屏幕组件传递到PokedexRow作为道具。
renderItem = ({item}) => <PodexRow navigation={this.props.navigation} name={item.name} />;