I need your help to explain about differences between arrow function and normal function in React Native code. Does this code :
updateState = () => this.setState({myState: 'The state is updated'})
is equivalent with this one:
updateState () {
this.setState({myState: 'The state is updated'})
}
if the answer is YES, why this code is working fine :
import React, {Component} from 'react';
import { Text, View } from 'react-native';
export default class App extends Component {
state = {
myState: 'This is a text component, created using state data. It will change or updated on clicking it.'
}
updateState = () => this.setState({myState: 'The state is updated'})
render() {
return (
<View>
<Text onPress={this.updateState}> {this.state.myState} </Text>
</View>
);
}
}
but, why this code is not working?
import React, {Component} from 'react';
import { Text, View } from 'react-native';
export default class App extends Component {
state = {
myState: 'This is a text component, created using state data. It will change or updated on clicking it.'
}
updateState () {
this.setState({myState: 'The state is updated'})
}
render() {
return (
<View>
<Text onPress={this.updateState}> {this.state.myState} </Text>
</View>
);
}
}
but if the answer is NO, why both code below is working fine, when I change
onPressButton() {
Alert.alert('You clicked the button!')
}
to
onPressButton = () => {
Alert.alert('You clicked the button!')
}
First Code :
import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';
export default class ButtonBasics extends Component {
onPressButton() {
Alert.alert('You clicked the button!')
}
render() {
return (
<View style={styles.container}>
<View>
<Button
onPress={this.onPressButton}
title="Press Me"
/>
</View>
</View>
);
}
}
and second code:
import React, { Component } from 'react';
import { Alert, AppRegistry, Button, StyleSheet, View } from 'react-native';
export default class ButtonBasics extends Component {
onPressButton = () => {
Alert.alert('You clicked the button!')
}
render() {
return (
<View>
<View>
<Button
onPress={this.onPressButton}
title="Press Me"
/>
</View>
</View>
);
}
}
Both above code is running perfectly
I'am really confused about this, and Need your help about this matter.
Thanks in advance