小编典典

找不到变量:导航

reactjs

我正在尝试借助来在两个屏幕之间导航react- navigation。我可以navigaterender方法内部访问,因为它的范围也在该方法内部。

我应该在哪里声明,以便可以使用this的任何方法进行访问component。我正在尝试访问方法navigate内部,onPressButton但它给出了错误。

找不到变量:导航

import React, { Component } from "react";
import { View, Text, Image, Button, Alert, StyleSheet } from "react-native";
import styles from "./Styles";
import * as strings from "./Strings";
import RoundButton from "./RoundButton";
var DialogAndroid = require("react-native-dialogs");
import { StackNavigator } from "react-navigation";

export default class CreateMessageScreen extends Component {
  render() {  
    const { navigate } = this.props.navigation;

    return (
      <View style={styles.container}>
        <Image source={require("./img/create_message.png")} />
        <Text style={styles.textStyle}>{strings.create_message}</Text>

        <RoundButton
          textStyle={styles.roundTextStyle}
          buttonStyle={styles.roundButtonStyle}
          onPress={this.onPressButton}
        >
          CREATE MESSAGE
        </RoundButton>

      </View>
    );
  }

  onPressButton() {
    var options = {
      title: strings.app_name,
      content: strings.create_message,
      positiveText: strings.OK,
      onPositive: () => navigate("DashboardScreen")
    };
    var dialog = new DialogAndroid();
    dialog.set(options);
    dialog.show();
  }
}

阅读 341

收藏
2020-07-22

共1个答案

小编典典

您需要const { navigate } = this.props.navigation;进入onPressButton函数而不是render函数中(不要忘记bind使用函数,以便this具有正确的值):

export default class CreateMessageScreen extends Component {
  constructor() {
    super();

    // need to bind `this` to access props in handler
    this.onPressButton = this.onPressButton.bind(this);
  }

  render() {  
    return (
      <View style={styles.container}>
        <Image source={require("./img/create_message.png")} />
        <Text style={styles.textStyle}>{strings.create_message}</Text>

        <RoundButton
          textStyle={styles.roundTextStyle}
          buttonStyle={styles.roundButtonStyle}
          onPress={this.onPressButton}
        >
          CREATE MESSAGE
        </RoundButton>

      </View>
    );
  }

  onPressButton() {
    const { navigate } = this.props.navigation;

    var options = {
      title: strings.app_name,
      content: strings.create_message,
      positiveText: strings.OK,
      onPositive: () => navigate("DashboardScreen")
    };
    var dialog = new DialogAndroid();
    dialog.set(options);
    dialog.show();
  }
}
2020-07-22