javascript - 反应本机文本颜色不起作用
问题描述
我在 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
但没有结果。我也尝试在样式变量中使用它,但同样不起作用。
任何的想法?
解决方案
该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>
);
}
}
推荐阅读
- r - 无法将 README.Rmd 推送到 GitHub
- python - 多索引列数据框 - 在 read_excel 末尾添加了额外的列
- html - 如何将部分导航内容向右对齐?
- c# - 在 SOAP 请求 .NET CORE 2.2 上发送的 Http.WinHttpException。收到的消息是意外的或格式错误
- gcc - 如何告诉 MOC(QT) 排除与 gcc 相关的包含以避免出现以下问题:“std”处的解析错误?
- javascript - 你好。为什么不应用“不显示”
- javascript - 为什么静音播放时会出现音频错误
- python - Python:字符串到受控词汇
- visual-studio-code - 退格键和箭头在 windows10 中的 VS Code 的 Bash 终端上不起作用
- c++ - C++中的右移转换