gpt4 book ai didi

javascript - react native 文本颜色不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 13:08:28 25 4
gpt4 key购买 nike

我在 TouchableOpacity 中有一个 Text 组件,我想根据 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>
);
}
}

关于javascript - react native 文本颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51663457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com