【问题标题】:Creation of a new component with navigation fields使用导航字段创建新组件
【发布时间】:2019-08-06 15:35:54
【问题描述】:

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

undefined 不是对象(评估 '_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'}/>

【问题讨论】:

  • 你可能忘记在父组件中发送navigation 作为prop。
  • 请给我看一下传递数据的代码。
  • @hongdevelop 我只是编辑帖子

标签: react-native react-native-navigation


【解决方案1】:

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

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

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

然后你可以这样做:

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

navigation.navigate(..)

【讨论】:

    【解决方案2】:

    你可以改变这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      相关资源
      最近更新 更多