为什么我无法在本机警报中访问this.props.navigation?

时间:2017-06-16 17:11:43

标签: react-native alert react-navigation

Alert.alert(
      '',
      'Kindly Select from the following Actions',
      [
        {
          text: 'Edit',
          onPress: () => this.props.navigation.navigate(
            'PositionForm',
            {
              formType: 'edit',
              item: this.props.position
            }
          )
        },
        { text: 'Delete', onPress: () => console.log('delete Pressed') },
      ]
    );

我正在寻找一个解决方案。我想在警报点击编辑按钮时导航到另一个页面。我正在使用react-navigation和redux。请帮助。 提前谢谢。

完整组件COde如下:

import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';

class PositionItem extends Component {
  showAlert() {
    Alert.alert(
      '',
      'Kindly Select from the following Actions',
      [
        {
          text: 'Edit',
          onPress: () => this.props.navigation.navigate(
            'PositionForm',
            {
              formType: 'edit',
              item: this.props.position
            }
          )
        },
        { text: 'Delete', onPress: () => console.log('delete Pressed') },
      ]
    );
  }

  render() {
    const {
      positionContainer,
      textStyle,
      iconsStyle,
      positionName,
      starIconStyle
    } = styles;
    const {
      name
    } = this.props.position;
    return (
      <TouchableOpacity onPress={this.showAlert.bind(this)}>
        <View style={positionContainer}>
          <View style={positionName}>
            <Text style={textStyle}>{name}</Text>
          </View>
          <View style={iconsStyle}>
            <Icon style={starIconStyle} name="star-o" size={30} color="#ccc" />
            <Icon name="angle-right" size={30} color="#ccc" />
          </View>
        </View>
      </TouchableOpacity>
    );
  }
}

const styles = StyleSheet.create({
  positionContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingTop: 15,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderColor: '#ccc'
  },
  textStyle: {
    marginBottom: 0,
    color: '#333333',
    fontSize: 20,
    fontWeight: '600',
    borderLeftWidth: 6,
    borderColor: '#cccccc',
    paddingLeft: 20,
    paddingTop: 5,
    paddingBottom: 5,
    lineHeight: 20
  },
  iconsStyle: {
    flexDirection: 'row',
    flex: 20,
  },
  starIconStyle: {
    paddingTop: 2,
    paddingRight: 15
  },
  positionName: {
    flex: 80
  }
});

export default PositionItem;

1 个答案:

答案 0 :(得分:1)

我看不出问题,但更糟糕的是你可以把变量放在较高的范围内。

showAlert() {
    const {navigation, position} = this.props
    Alert.alert(

此外,我不想绑定和使用新语法来创建类字段,你总是得到正确的。

showAlert = () => {
    ...
}

<TouchableOpacity onPress={this.showAlert}>
相关问题