是否有一种有效的方法可以通过考虑传递的值来为元素分配颜色,而不用对每个组件重复代码?
例如我有这个:
如果
value :'high'
文本颜色应为red
。如果
value :'low'
文本颜色应为green
。- 等....
这是我的代码,但我必须将 switch
语句添加到我的所有组件中,它看起来很杂乱,尤其是要添加更多颜色。
const list1 = [
{
title: 'One',
temperature: 'very high',
},
{
title: 'Two',
temperature: 'high',
},
{
title: 'Three',
temperature: 'medium',
},
{
title: 'Four',
temperature: 'low',
},
{
title: 'Five',
temperature: 'very low',
},
];
export default class Regional extends Component {
constructor(props) {
super(props);
this.state ={
dataSource: list1
}
}
render() {
const { dataSource } = this.state;
const showData = dataSource.map((l, i) => {
let myColor = 'blue';
switch (l.temperature) {
case 'high':
myColor = 'red';
break;
case 'medium':
myColor = 'yellow';
break;
case 'low':
myColor = 'green';
break;
default:
myColor = 'grey';
}
return(
<View style={{flex: 1, flexDirection: 'column'}} key={i}>
<Text style={{flex: 1, color:myColor}}>{l.temperature}</Text>
</View>
)
})
return (
<View>
{showData}
</View>
)
}
}
这很好用,但我在很多组件中都有这个。
如果这是最好的解决方案并且不会变得复杂,我会很高兴,因为它只是重复和额外的行。
欢迎任何建议。谢谢!
最佳答案
您可以有一个对象 colors
,其中键是不同的温度,值是颜色。如果温度不是对象的属性,您可以回退到 'grey'
。
const colors = {
high: "red",
medium: "yellow",
low: "green"
};
class Regional extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource: list1
};
}
render() {
const { dataSource } = this.state;
const showData = dataSource.map((l, i) => {
let myColor = colors[l.temperature] || "grey";
return (
<View style={{ flex: 1, flexDirection: "column" }} key={i}>
<Text style={{ flex: 1, color: myColor }}>{l.temperature}</Text>
</View>
);
});
return <View>{showData}</View>;
}
}
关于javascript - 为数据分配颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51773311/