javascript-找不到变量:导航

我试图借助react-navigation在两个屏幕之间导航.我能够访问render方法内部的导航,因为它的范围也在该方法内部.

我应该在哪里声明,以便可以访问此组件的任何方法.我正在尝试在onPressButton方法内部访问导航,但它给出了错误.

Can’t find variable: navigate

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();
  }
}

解决方法:

您需要移动const {navigation} = this.props.navigation;.放到onPressButton函数中,而不是在render函数中放进去(不要忘记绑定该函数,使其具有正确的值):

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();
  }
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...