Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Text color not working

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?

like image 754
MohamadKh75 Avatar asked Aug 02 '18 23:08

MohamadKh75


1 Answers

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>
    );
  }
}
like image 150
Tholle Avatar answered Nov 13 '22 20:11

Tholle