Moh*_*h75 4 javascript android reactjs react-native
我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"
}
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用this.state.textColor
但没有结果。我也曾尝试在styles变量中使用它,但同样不能正常工作。
任何的想法?
该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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8284 次 |
最近记录: |