Component LifeCycle and State of React Native
Codes:
import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
export default class App extends React.Component {
constructor() {
super();
this.state = {
counter: 0,
buttonColor: 'black',
};
}
increment = () => {
this.setState({
counter: this.state.counter + 1,
});
};
changeColor = () => {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
this.setState({ buttonColor: color });
};
componentDidMount() {
setInterval(this.increment, 1000);
}
componentDidUpdate() {
// console.log("Updated")
console.log(this.state.buttonColor);
}
render() {
return (
<View style={styles.container}>
<View style={styles.heading}>
<Text style={styles.headText}>Component LifeCycle and State</Text>
</View>
<View style={styles.counterContainer}>
<Text style={styles.counter}>{this.state.counter}</Text>
</View>
<View>
<TouchableOpacity
style={[styles.button, { backgroundColor: this.state.buttonColor }]}
onPress={() => {
this.changeColor();
}}>
<Text style={styles.buttonText}>Press Me</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
heading: {
backgroundColor: 'cyan',
width: 333,
height: 60,
textAlign: 'center',
justifyContent: 'center',
},
headText: {
fontWeight: 'bold',
fontStyle: 'italic',
fontSize: 20,
},
button: {
borderWidth: 2,
width: 200,
height: 50,
marginTop: 50,
textAlign: 'center',
},
buttonText: {
color: 'white',
fontSize: 20,
marginTop: 10,
},
counterContainer: {
marginTop: 50,
borderWidth: 1,
width: 50,
height: 50,
textAlign: 'center',
justifyContent: 'center',
backgroundColor: 'yellow',
},
counter: {
fontSize: 20,
fontWeight: 'bold',
},
});
0 Comments: