I just want to know how to call a function onPress
. I've setup my code like this:
export default class Tab3 extends Component {
constructor(props) {
super(props);
this.state = {myColor: "green"};
}
handleClick = () => {
if (this.state.color === 'green'){
this.setState({myColor: 'blue'});
} else {
this.setState({myColor: 'green'});
}
}
render() {
return(
<View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={() => handleClick(this)}
/>
</View>
)};
But when I try this, I'm getting error that can't find variable handleClick
Please help. I just want to know how to bind a function to a click event.
To bind onPress with an argument in React Native, we can create a function that returns the onPress handler function. to add a Button with the onPress prop set to the function that we get after we call onPress with 'hello' .
To call a function, you can either pass its name and arguments to User. callFunction() or call the function as if it was a method on the User.
To call multiple functions when onPress is clicked with React Native, we can assign onPress to a function that calls all the functions. to define the onPress function that calls foo , bar , and baz . Then we set the onPress prop to the onPress function.
Example: Call a Function After Clicking a Buttonimport React from 'react'; function App() { function sayHello() { alert('Hello!' ); } return ( <button onClick={sayHello}> Click me!
A little late to the party, but just wanted to leave this here if someone needs it
export default class mainScreen extends Component {
handleClick = () => {
//some code
}
render() {
return(
<View>
<Button
name='someButton'
onPress={() => {
this.handleClick(); //usual call like vanilla javascript, but uses this operator
}}
/>
</View>
)};
In you're render you're setting up the handler incorrectly, give this a try;
<View>
<Icon
name='heart'
color={this.state.myColor}
size= {45}
style={{marginLeft:40}}
onPress={this.handleClick}
/>
</View>
The syntax you're using would make sense for declaring an anonymous function inline or something but since your handler is defined on the class, you just reference it (not call it) using this.functionName
in the props.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With