创建带有导航字段的新组件

Creation of a new component with navigation fields

我尝试创建一个包含两个按钮的新 react-native 组件。我定义了两个 属性 next 去下一页和 prev 去上一页但是我有这个错误:

undefined is not an object (evaluating '_this.props.navigation.navigate')

我发现了很多类似的问题,但我没有找到任何有效的解决方案。

这是代码:

import PropTypes from 'prop-types'
import React, { Component } from 'react';
import { View, StyleSheet, Button } from 'react-native';

export default class ButtonNavigation extends Component {

  static propTypes = {
    next: PropTypes.string,
    prev: PropTypes.string,
  }

  render() {

    const { next, prev } = this.props;

    return (
      <View style={styles.bottomContainer}>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.navigation.navigate(next)} title='Indietro' color='#00b0ff'/>
        </View>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.navigation.navigate(prev)} title='Avanti' color='gold'/>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  bottomContainer: {
    flex: 1,
    flexDirection: 'row',
    position: 'absolute',
    bottom: 10,
    padding: 20,
    justifyContent: 'space-between'
  },
  text: {
    fontSize: 30,
  },
  buttonContainer: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignContent: 'center',
  }
});

我是这样在其他页面中包含对象的:

<ButtonNavigation next={'NumberVehicle'} prev={'Home'}/>

在您的 <ButtonNavigation next={'NumberVehicle'} prev={'Home'}/> 中,您需要将导航对象添加为道具。所以像:

<ButtonNavigation
  next={'NumberVehicle'}
  prev={'Home'}
  navigation={this.props.navigation} 
/>

(如果与实际导航对象不同,请务必替换this.props.navigation

然后你可以做:

const { next, prev, navigation } = this.props;

navigation.navigate(..)

你可以改变这个

<ButtonNavigation next={this.props.navigation.navigate('NumberVehicle')} prev={this.props.navigation.navigate('Home')}/>
      <View style={styles.bottomContainer}>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.next} title='Indietro' color='#00b0ff'/>
        </View>
        <View style={styles.buttonContainer}>
          <Button onPress={() => this.props.prev} title='Avanti' color='gold'/>
        </View>
      </View>