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

时间:2019-08-06 15:35:54

标签: react-native react-native-navigation

我尝试创建一个包含两个按钮的新react-native组件。我在下一页中定义了两个属性next,在上一个页面中定义了两个属性prev,但出现此错误:

  

未定义不是对象(正在评估'_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'}/>

2 个答案:

答案 0 :(得分:1)

您需要在<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(..)

答案 1 :(得分:0)

您可以更改

<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>