首页 > 解决方案 > 反应本机文本颜色不起作用

问题描述

我在 a 中有一个Text组件TouchableOpacity,我想根据 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但没有结果。我也尝试在样式变量中使用它,但同样不起作用。

任何的想法?

标签: javascriptandroidreactjsreact-native

解决方案


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

而是将其置于您的组件状态并切换它,setState它将起作用。

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

推荐阅读