反应原生文本颜色不起作用 [英] React Native Text color not working

查看:38
本文介绍了反应原生文本颜色不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 TouchableOpacity 中有一个 Text 组件,我想根据 var 更改颜色.

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

这是我的代码:

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"
  }
});

我尝试使用 this.state.textColor 但没有结果.我也试过在样式变量中使用它,但同样没有用.

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.

有什么想法吗?

推荐答案

flag 变量不在您的组件状态中,因此组件在更改时不会重新渲染.

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

把它放在你的组件状态,然后用 setState 切换它,它就会工作.

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>
    );
  }
}

这篇关于反应原生文本颜色不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆