【问题标题】:How can I navigate from one page to another in React-Native? I try to use navigation, but I get the error: Invalid hook call如何在 React-Native 中从一个页面导航到另一个页面?我尝试使用导航,但出现错误:无效的挂钩调用
【发布时间】:2025-12-13 22:30:02
【问题描述】:

我有一个类可以呈现一个按钮,该按钮应该将我重定向到另一个页面。我可以像我一样使用通过在 render() 中使用 useNavigation() 创建的导航器吗?我不这么认为,因为我尝试过这种方式,但没有奏效。你能告诉我如何解决这个问题吗? 当我尝试通过在功能组件中转换类来使用它时,我设法让它工作。但我想在课堂上做同样的事情。

export class PetList extends Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {pets:[]};
    }
 
    render() {
        let navigation = useNavigation();
        return (
            <View style={styles.bigContainer}>
                <Card containerStyle={styles.container}>
                    <Card containerStyle={styles.container}>
                        <Card.Title style={styles.title}> MY PETS</Card.Title>
                        <Card.Divider/>
                        {
                            this.state.pets.map((u:any, i:any) => {
                                return (
                                    <Card key={i} containerStyle={styles.container}>
                                        <View style={styles.pet}>
                                            <Image
                                                style={styles.image}
                                                resizeMode="cover"
                                                source={require('../photos/' + String(3) + '.jpg' )}
                                                alt="Pet photo"
                                            />
                                            <View style={styles.text}>
                                                <Text style={styles.name}>{u.name} </Text>
                                                <Text style={styles.description}>{u.description} </Text>
                                            </View>
                                        </View>
                                    </Card>
                                );
                            })
                        }
                    </Card>
                    <Button onPress={() => navigation.navigate('addPetForm')}>+</Button>
                </Card>
            </View>
        );
    }
}

【问题讨论】:

    标签: typescript react-native navigation


    【解决方案1】:

    如果设置正确,React native 会将导航器作为道具传递。假设您使用功能组件使其工作,您应该能够通过{navigation} = this.props 语法提取导航道具。

    【讨论】:

      最近更新 更多