You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native类组件使用react-native-app-intro-slider点击按钮navigation报错求助

问题原因
  • onGetStartedPressed 定义在类组件外部,作为独立的普通函数,this 不指向Start类的组件实例,无法获取到组件实例上挂载的props.navigation,这是触发报错的直接原因
  • onGetStartedPressed 内部的跳转逻辑存在语法错误:你定义了() => navigate('Sgnin')这个匿名函数但没有主动执行,就算上下文正确也无法触发跳转
  • 额外排查点:需确认Start页面已注册到你使用的导航器(如React Navigation的Stack.Navigator)中,未注册的页面不会默认注入navigation属性
修复方案

修改后的完整代码如下,核心改动是把跳转方法移到类内部,修正跳转逻辑:

import React from 'react';
import {View, StatusBar, Image, SafeAreaView, Text, Button} from 'react-native';
import AppIntroSlider from 'react-native-app-intro-slider';

import styles from './styles';
type Item = typeof slides[0];

const slides = [
  {
    key: 'one',
    title: 'item 1',
    image: Images.surb1,
    bg: '#59b2ab',
  },
  {
    key: 'two',
    title: 'item 2',
    image: Images.surb2,
    bg: '#febe29',
  },
  {
    key: 'three',
    title: 'item 3',
    image: Images.surb3,
    bg: '#22bcb5',
  },
  {
    key: 'four',
    title: 'item 4',
    image: Images.surb4,
    bg: '#0b76a2',
  },
];
export default class Start extends React.Component {
  constructor() {
    super();
  }
  // 类内部定义的箭头函数,this固定指向当前组件实例
  onGetStartedPressed = () => {
    const {navigate} = this.props.navigation;
    // 直接执行跳转,注意检查目标页面名称拼写,原代码的Sgnin大概率是Signin的笔误
    navigate('Signin');
  };

  _renderItem = ({item}: {item: Item}) => {
    return (
      <View
        style={{
          flex: 1,
          backgroundColor: item.bg,
        }}>
        <SafeAreaView style={styles.slide}>
          <Text style={styles.title}>{item.title}</Text>
          <Image source={item.image} style={styles.image} />
        </SafeAreaView>
      </View>
    );
  };

  _keyExtractor = (item: Item) => item.title;
  _renderDoneButton = () => {
    return (
      <Button
        full
        style={{marginTop: 20}}
        onPress={this.onGetStartedPressed}
      >
        Get Started
      </Button>
    );
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <StatusBar translucent backgroundColor="transparent" />
        <AppIntroSlider
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          renderDoneButton={this._renderDoneButton}
          bottomButton
          showSkipButton
          data={slides}
        />
      </View>
    );
  }
}

如果确认页面已经注册到导航栈但还是拿不到navigation属性,可以用withNavigation高阶组件包裹导出:

  1. 导入对应依赖:import { withNavigation } from '@react-navigation/compat';
  2. 修改导出语句为:export default withNavigation(Start);

内容的提问来源于stack exchange,提问作者MIike Eps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 16:45:01