我试图借助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();
}
}