Reputation: 161
First off I want to say I am new to react-native and react in general so if I am doing things totally wrong, let me know.
Currently I am building an application with a login function in react-native 0.48.4. First off I want to make a hard-coded login function before I am going to work with API calls, my project structure is like this:
export default class LoginScreenComponent extends Component {
render () {
return (
<KeyboardAvoidingView behavior={'padding'} style={styles.loginContainer}>
<LogoComponent/>
<TextLogoComponent/>
<LoginFormComponent login={() => { this.login(); }}/>
</KeyboardAvoidingView>
);
}
login (email, password) {
console.log(email); //prints undefined
if (email == 'test' && password == 'test') {
this.props.navigation.navigate('LoggedIn');
} else {
Alert.alert(
'Oops',
'Wrong username or password, please try again.',
[
{text: 'OK'},
],
{ cancelable: false }
);
}
}
}
As you can see I am passing a login function as property to the LoginFormComponent.
export default class LoginFormComponent extends Component {
constructor (props) {
super(props);
}
state = {
email: '',
password: '',
};
render () {
return (
<View style={styles.container}>
<UserInput placeholder={'E-mail'} onChangeText={(email) => this.setState({email})} value={this.state.email}/>
<UserInput placeholder={'Password'} onChangeText={(password) => this.setState({password})} value={this.state.password} secureTextEntry={true}/>
<Button text={'Login'} onPress={() => {this.onLoginPress(); }}/>
<TouchableHighlight>
<Text style={styles.text}>
Forgot password?
</Text>
</TouchableHighlight>
</View>
);
}
onLoginPress () {
console.log(this.state.email); //prints the email correctly
this.props.login(this.state.email, this.state.password);
}
}
LoginFormComponent.propTypes = {
login: PropTypes.func.isRequired
}
In the LoginFormComponent I call the function onLoginPress () which calls the property function login with as parameter this.state.email and this.state.password. If I execute this code this.state.email (And this.state.password) is defined before passing it through the this.props.login function but undefined when it reaches the actual login function. My question is, what is the correct way to pass parameters through property functions in react-native?
Example console log when pressing the button:
[email protected] undefined
Upvotes: 0
Views: 3711
Reputation: 358
Change line to:
<LoginFormComponent login={(email, password) => { this.login(email, password); }}/>
In the above mentioned line you were not accepting any parameters thus the function login(email, password)
is not receiving any parameter. This leads to email
and password
values as undefined
.
Upvotes: 2