警告:失败道具类型道具" onPress"在"按钮"中标记为必需,但其值为"未定义"

时间:2018-06-13 20:17:05

标签: javascript reactjs react-native

我定义了prop _navigateToRegister,但是当我按下按钮时没有任何反应。 而且我也有这个错误警告:警告:失败的道具类型道具" onPress"在"按钮"中标记为必需,但其值为"未定义" 错误在哪里?

app.js

import React, { Component } from 'react';
import {
AppRegistry
} from 'react-native';
import {
StackNavigator,
} from 'react-navigation';
import { createStackNavigator } from 'react-navigation';
import Login from './src/screens/Login';
import Secured from './src/screens/Secured';
import Register from './src/screens/Register';

const LifeStorm = createStackNavigator({
Login: { screen: Login },
Register: { screen: Register },
Secured: { screen: Secured },
});

export default class ReactNativeStormpath extends Component {

state = {
isLoggedIn: false
}

render() {

if (this.state.isLoggedIn)
  return <Secured
      onLogoutPress={() => this.setState({isLoggedIn: false})}
    />;
else
  return <Login
      onLoginPress={() => this.setState({isLoggedIn: true})}
    />;
}

}

AppRegistry.registerComponent("App", () => App);

login.js

import React, { Component } from "react";
import { ScrollView, Text, TextInput, View, Button } from "react-native";

export default class Login extends Component {

navigateToRegister = () => {
this.props.navigation.navigate("Register");
};

render() {
return (
  <ScrollView style={{ padding: 20 }}>
    <Text style={{ fontSize: 27 }}>Login</Text>
    <TextInput placeholder="Username" />
    <TextInput placeholder="Password" />
    <View style={{ margin: 7 }} />
    <Button onPress={this.props.onLoginPress} title="Submit" />
    <Button onPress={this.props._navigateToRegister} title = "Register" />
  </ScrollView>
);
}
}

module.exports = Login;

register.js

import React, { Component } from 'react';
import {
ScrollView,
Text,
TextInput,
View,
Button
} from 'react-native';

export default class Register extends Component {
render() {
    return (
        <ScrollView style={{padding: 20}}>
            <Text
                style={{fontSize: 27}}>
                Register
            </Text>
            <TextInput placeholder='E-Mail' />
            <TextInput placeholder='Username' />
            <TextInput placeholder='Password' />
            <TextInput placeholder='Confirm Password' />
            <View style={{margin:7}} />
            <Button
                    onPress={() => navigate("Login")}
                    title="Submit"
                />
            </ScrollView>
        )
   }
   }

P.S我是React Native的新手。

1 个答案:

答案 0 :(得分:0)

在我看来,你实际上并没有将_navigateToRegister道具发送给组件。

这意味着如果您将this.props._navigateToRegister记录到控制台,该事件的结果应为undefined。而且因为你要向onPress发送未定义的值,你会得到那个道具类型错误。

如果您想引用Login组件的navigateToRegister方法,可以这样做:

<Button onPress={this.navigateToRegister} title = "Register" />