微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐