Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  54] [ 4]  / answers: 1 / hits: 56115  / 7 Years ago, mon, august 7, 2017, 12:00:00

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.


More From » reactjs

 Answers
157

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.


[#56840] Friday, August 4, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danar

Total Points: 271
Total Questions: 94
Total Answers: 93

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
;