我想知道如何使用组件内部的useNavigation()功能在React Navigation模块中从一个屏幕导航到另一个屏幕。根据文档,您必须通过在我的标签(此处为)内包含onPress来包含useNavigation()函数。问题是它向我显示了以下错误:'不变违规:无效的通话。挂钩只能在功能组件的主体内部调用。'
我的React Native组件:
import React, { Component } from 'react';
import {View, StyleSheet, Image, TouchableOpacity} from "react-native";
import { Text } from 'react-native-elements';
import { LinearGradient } from 'expo-linear-gradient';
import PropTypes from 'prop-types';
import { useNavigation } from '@react-navigation/native';
export default class HorizontalCard extends Component {
static propTypes = {
screen: PropTypes.string,
title: PropTypes.string,
desc: PropTypes.string,
img: PropTypes.string,
}
render() {
const navigation = useNavigation();
return (
<TouchableOpacity onPress={() => navigation.navigate(this.props.screen)} style={styles.container}>
<View style={styles.card_discord}>
<Image style={styles.card_discord_img} source={{uri: this.props.img}} />
<LinearGradient
start={[1.0, 0.5]}
end={[0.0, 0.5]}
colors={['rgba(42, 159, 255, 0.2)', '#333333', '#333333']}
style={styles.FadeAway}>
<View style={styles.FadeAway}>
<Text h4 style={styles.FadeAway_h2}>{this.props.title}</Text>
<Text style={styles.FadeAway_p}>{this.props.desc}</Text>
</View>
</LinearGradient>
</View>
</TouchableOpacity>
)
}
}
谢谢。问候,
Quentin
如果要使用classes
,则不能将组件实现为hooks
。
因此,如果要使用hooks
,则应将组件实现为functions
,因为hooks
只能在function component
的内部调用。
因此,您的组件应如下所示。
import React from 'react';
import { View, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { Text } from 'react-native-elements';
import { LinearGradient } from 'expo-linear-gradient';
import PropTypes from 'prop-types';
import { useNavigation } from '@react-navigation/native';
export function HorizontalCard(props) {
const navigation = useNavigation();
return (
<TouchableOpacity
onPress={() => navigation.navigate(props.screen)}
style={styles.container}>
<View style={styles.card_discord}>
<Image style={styles.card_discord_img} source={{ uri: props.img }} />
<LinearGradient
start={[1.0, 0.5]}
end={[0.0, 0.5]}
colors={['rgba(42, 159, 255, 0.2)', '#333333', '#333333']}
style={styles.FadeAway}>
<View style={styles.FadeAway}>
<Text h4 style={styles.FadeAway_h2}>
{props.title}
</Text>
<Text style={styles.FadeAway_p}>{props.desc}</Text>
</View>
</LinearGradient>
</View>
</TouchableOpacity>
);
}
HorizontalCard.propTypes = {
screen: PropTypes.string,
title: PropTypes.string,
desc: PropTypes.string,
img: PropTypes.string,
};
您不能在Class组件内部使用钩子,因为它在错误中明确指出。请检查[反应文档] [1]