开发者问题收集

简单的 React Native 类的问题

2021-07-08
213

我对 react-native 有点陌生,现在我真的被 React Natives 类组件难住了

我正在使用 react-native-app-intro-slider 构建一个演示屏幕

在我点击“开始”按钮之前,一切都运行良好

查看我点击按钮时出现的错误

错误 TypeError:未定义不是对象(评估'_this.props.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 onGetStartedPressed = () => {
  const {navigate} = this.props.navigation;
  () => navigate('Sgnin');
};
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();
  }

  _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={() => 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>
    );
  }
}
2个回答

您需要在 onGetStartedPressed 方法中传递 props

<Button
        full
        style={{marginTop: 20}}
        onPress={() => onGetStartedPressed(this.props)}>
        Get Started
</Button>

并编辑 onGetStartedPressed 方法

const onGetStartedPressed = (props) => {
  props.navigation.navigate('Sgnin');
};
edhi.uchiha
2021-07-08

您的函数在类之外,因此对于该函数, props 未定义。您需要将该函数放在类内。

export default class Start extends React.Component {
  constructor() {
    super();
  }

  onGetStartedPressed = () => {
    const {navigate} = this.props.navigation;
    navigate('Sgnin');
  };

并将此: onPress={() => onGetStartedPressed()

替换为: onPress={() => this.onGetStartedPressed()

Tayyab Mazhar
2021-07-08