Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  114] [ 5]  / answers: 1 / hits: 57713  / 6 Years ago, thu, august 2, 2018, 12:00:00

I've got a Text component inside a TouchableOpacity which I want to change the color depend on a var.



Here is my code:



import React, { Component } from react;
import { StyleSheet, Text, View, TouchableOpacity } from react-native;

var flag = false;

export default class MyTest extends Component {
changeColor() {
flag = true;
}

render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={{ flex: 1, backgroundColor: #888888, margin: 20 }}
onPress={this.changeColor.bind(this)}
>
<Text style={[{ color: blue }, flag ? { color: red } : false]}>
One
</Text>
</TouchableOpacity>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: center,
backgroundColor: #F5FCFF
}
});


I have tried to use this.state.textColor but no result. I've also tried to use that in styles variable but again, not working.



Any idea?


More From » android

 Answers
28

The flag variable is not in your component state, so the component will not re-render when it changes.



Put it in your component state instead and toggle it with setState and it will work.



class MyTest extends Component {
state = { flag: true };

changeColor = () => {
this.setState(previousState => {
return { flag: !previousState.flag };
});
};

render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={{ flex: 1, backgroundColor: #888888, margin: 20 }}
onPress={this.changeColor}
>
<Text style={{ color: this.state.flag ? red : blue }}>One</Text>
</TouchableOpacity>
</View>
);
}
}

[#53816] Tuesday, July 31, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lizet

Total Points: 479
Total Questions: 96
Total Answers: 113

Location: Mexico
Member since Sun, Jul 25, 2021
3 Years ago
;