React Native Text color not working
42,053
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>
);
}
}
Comments
-
MohamadKh75 over 2 years
I've got a
Text
component inside aTouchableOpacity
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?