无法 运行 React native 中自定义后退按钮的反应导航功能

Unable to run react-navigation functions on customised back button in React native

我无法使用的功能 运行 是我示例中的导航功能

this.this.props.navigation.goBack()

我的登录文件已发布在下面,但有问题的部分是短片段

我收到的错误是:TypeError: undefined is not an object (evaluating 'LogIn.props.navigation')

第一个失败的代码段

static navigationOptions = {
        headerLeft: () => (
          <Button
            onPress={()=>this.props.navigation.goBack()}
            title="cancel"
            color={colors.black}
          />
        ),
    };

LogIn.js

import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import Icon from 'react-native-vector-icons/FontAwesome';
import colors from '../styles/colors';
import {
  View,
  Text,
  ScrollView,
  StyleSheet, 
  KeyboardAvoidingView,
  Button
} from 'react-native';

import InputField from '../components/form/InputField';
import NexArrowButton from '../components/buttons/NextArrowButton';
import Notification from '../components/Notification';


export default class LogIn extends Component{

    constructor(props){
        super(props);
        this.state ={
            formValid:false,
            validEmail:false,
            emailAddress:'',
            validPassword:false,
        }

        this.handleNextButton = this.handleNextButton.bind(this)
        this.handleCloseNotification = this.handleCloseNotification.bind(this)
        this.handleEmailChange = this.handleEmailChange.bind(this);
    }

    static navigationOptions = {
        headerLeft: () => (
          <Button
            onPress={()=>this.props.navigation.goBack()}
            title="cancel"
            color={colors.black}
          />
        ),
    };

    handleNextButton(){
        if(this.state.emailAddress === 'admin@mail.com'){
            this.setState({formValid:true})
        } else{
            this.setState({formValid: false});
        }
    }

    handleCloseNotification(){
        this.setState({formValid:true });
    }

    handleEmailChange(email){
        const emailCheckRegex = /^(([^<>()\[\]\.,;:\s@"]+(\.[^<>()\[\]\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        const { validEmail } = this.state;
        this.setState({ emailAddress: email });

        if (!validEmail) {
          if (emailCheckRegex.test(email)) {
            this.setState({ validEmail: true });
          }
        } else if (!emailCheckRegex.test(email)) {
          this.setState({ validEmail: false });
        }
    }

    handlePasswordChange(password){
        const { validPassword } = this.state;

        this.setState({ password });

        if (!validPassword) {
          if (password.length > 4) {
            // Password has to be at least 4 characters long
            this.setState({ validPassword: true });
          }
        } else if (password <= 4) {
          this.setState({ validPassword: false });
        }
    }



    render(){

        const {formValid, validPassword} = this.state;
        const showNotification = formValid ? false:true; 
        const background = formValid ? colors.green01 : colors.darkOrange;
        const notificationMarginTop =  showNotification ? 10:0;
        return(
            <KeyboardAvoidingView style={[{backgroundColor:background}, styles.wrapper] } behavior="padding">
                <View style={styles.ScrollViewWrapper}>
                    <ScrollView style={styles.ScrollView}>
                        <Text style={styles.loginHeader}>Log In</Text>
                        <InputField
                            labelText= "Email Address"
                            labelTextSize={20}
                            labelColor={colors.white}
                            textColor={colors.white}
                            borderBottomColor={colors.white}
                            inputType="email"
                            customStyle={{marginBottom:30}}
                            onChangeText={this.handleEmailChange}
                        />

                        <InputField
                            labelText= "Password"
                            labelTextSize={20}
                            labelColor={colors.white}
                            textColor={colors.white}
                            borderBottomColor={colors.white}
                            inputType="password"
                            customStyle={{marginBottom:30}}
                        />
                    </ScrollView>

                    <View style={styles.nextButton}>
                        <NexArrowButton
                            // handleNextButton={this.handleNextButton}
                            handleNextButton={()=>this.props.navigation.goBack()}

                        />
                    </View>

                    <View style={[styles.notificationWrapper, {marginTop:notificationMarginTop}]}>
                        <Notification
                            showNotification={showNotification}
                            handleCloseNotification={this.handleCloseNotification}
                            type="Error"
                            firstLine="Those credentials don't look right."
                            secondLine="Please try again."                            
                            /> 
                    </View>
                </View>
            </KeyboardAvoidingView>
        )
    }
}

const styles = StyleSheet.create({
    wrapper:{
        display:'flex',
        flex:1,
    },

    ScrollViewWrapper:{
        marginTop:60,
        flex:1,
    },

    ScrollView:{
        paddingLeft:30,
        paddingRight:30,
        paddingTop:10,
        flex:1,
    },

    loginHeader:{
        fontSize:34,
        color:colors.white,
        fontWeight:'300',
        marginBottom:40,
    },

    nextButton:{
        position:'absolute',
        right:20,
        bottom:20,
    },

    notificationWrapper:{
        position: 'absolute',
        bottom:0,
        zIndex:9
    }


});

最令人困惑的部分是 Login.js 下面的第二个片段完美地工作并且它本质上是同一件事,这意味着我得到了正确的道具,但仍然在自定义后退按钮中出现错误。

第二个工作片段

<View style={styles.nextButton}>
   <NexArrowButton
      // handleNextButton={this.handleNextButton}
      handleNextButton={()=>this.props.navigation.goBack()}
    />
</View>

App.js

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import LoggedOut from './src/screens/LoggedOut';
import LogIn from './src/screens/LogIn';
import LoggedIn from './src/screens/LoggedIn';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';


const RootStack = createStackNavigator(
  {
    LoggedOut: LoggedOut,
    LogIn: LogIn,
  },
  {
    initialRouteName: 'LoggedOut',
  }

);

const AppContainer = createAppContainer(RootStack);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

更详细的错误

非常感谢您的帮助!如果可以更轻松地调试,我很乐意提供更多代码。

如果您想在静态函数中访问导航属性,则必须将静态导航选项更改为以下代码段:

static navigationOptions = ({ navigation }) => ({
    headerLeft: () => (
      <Button
        onPress={()=>navigation.goBack()}
        title="cancel"
        color={colors.black}
      />
    ),
});

在这种情况下您不需要 this.props ;) 静态函数无法访问 this 上下文,因此 this.props 将不起作用。