Reputation: 167
I'm trying to make a form that submits values to an api that I have set up with this code
export default class login extends Component {
constructor(props) {
super(props);
this.state = { email: "test", password: "test" }
}
handleButtonPress() {
console.log("pressed");
params = {
email: this.state.email,
password: this.state.password
}
api.login(params)
}
render() {
return (
<View>
<FormLabel>Email</FormLabel>
<FormInput onChangeText={(email) => this.setState({email})}/>
<FormLabel>Password</FormLabel>
<FormInput secureTextEntry={true} onChangeText={(password) => this.setState({password})}/>
<Button
raised
icon={{name: 'check'}}
title='SUBMIT'
onPress={this.handleButtonPress()} />
</View>
);
}
}
The api is working as expected however the function handleButtonPress() Is being called every time I change text in my FormInput and when I click on the button I get a error of please attach method to this component
Any help is appreciated!
Upvotes: 2
Views: 3586
Reputation: 9674
Change:
<Button
raised
icon={{name: 'check'}}
title='SUBMIT'
onPress={this.handleButtonPress()} />
To:
<Button
raised
icon={{name: 'check'}}
title='SUBMIT'
onPress={() => this.handleButtonPress()} />
Edit:
When adding this.handleButtonPress()
to your onPress
props, you're immediately calling it. If you want to call that function, you have to wrap it with an anonymous arrow function like so onPress{() => this.myFunction()}
or you can just reference it like so onPress{this.myFunction}
. Both will work.
Upvotes: 3