Невозможно запустить функции реагирования-навигации на настраиваемой кнопке «Назад» в React native

Функция, которую я не могу запустить, - это функции навигации, в моем примере это

this.this.props.navigation.goBack()

Мой файл входа в систему размещен ниже, но проблема заключается в коротком фрагменте.

Я получаю сообщение об ошибке: TypeError: undefined не является объектом (оценка «LogIn.props.navigation»)

Первый неудачный сниппет

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

Логин.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 === '[email protected]'){
            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 />;
  }
}

Подробнее об ошибкеОшибка при нажатии кнопки

Я очень ценю вашу помощь ! Я буду рад предоставить больше кода, если это облегчит отладку.


person Cyborg_Patrick    schedule 27.12.2019    source источник


Ответы (1)


Вы должны изменить static navigationOptions на следующий фрагмент, если хотите получить доступ к свойствам навигации в статической функции:

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

В этом случае вам не нужен this.props ;) Статическая функция не имеет доступа к контексту this, поэтому this.props не будет работать.

person BigPun86    schedule 27.12.2019
comment
Вау, я не могу поверить, что это было так просто. Большое спасибо !. Но не могли бы вы подробнее объяснить, как это работает? - person Cyborg_Patrick; 27.12.2019