如何解决“react-native 导航错误”
2020-09-28
43
我正在制作一个口袋妖怪图鉴,我希望用户能够从
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*/
});
1个回答
因为 PokedexRow 不是自动获取导航 prop 的屏幕,所以你可以使用 useNavigation 作为功能组件来访问导航对象,或者将导航从屏幕组件传递到你的 PokedexRow 作为 prop。
renderItem = ({item}) => <PodexRow navigation={this.props.navigation} name={item.name} />;
Vivek_Neel
2020-09-28