reactjs - 我如何对道具值进行多次检查以更改该值的颜色。在 style={ } 的内部?
问题描述
我正在尝试构建一个列出要完成的任务的应用程序。在这些任务中,优先级编号为 1-5。我已经实现了一个解决方案,如果数字的值超过 2,则将该数字的颜色从绿色更改为黄色。但是,如果数字的值恰好为 5,我也希望该数字更改为红色。这怎么能做完了?
下面是 PrioLvl 组件的代码,该组件应该在其中发生此功能。
import { View, Text, Image, ScrollView, TextInput, StyleSheet } from 'react-native';
class PrioLvl extends React.Component {
constructor(props){
super(props)
}
render(){
return (
<View style={styles.container}>
<Text style={this.props.prio > 2 ? styles.yellow : styles.green}>{this.props.prio}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
width: 100,
},
green:{
fontSize: 50,
color: '#5cb85c'
},
yellow:{
fontSize: 50,
color: '#f0ad4e'
},
red: {
fontSize: 50,
color: '#d9534f'
}
});
export default PrioLvl;
解决方案
您可以将逻辑分解为辅助方法:
import { View, Text, Image, ScrollView, TextInput, StyleSheet } from 'react-native';
class PrioLvl extends React.Component {
constructor(props){
super(props)
}
getStyle = () => {
if (this.props.prio === 5) return 'red'
if (this.props.prio > 2) return 'yellow'
return 'green'
}
render(){
const style = this.getStyle()
return (
<View style={styles.container}>
<Text style={styles[style]}>{this.props.prio}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
width: 100,
},
green:{
fontSize: 50,
color: '#5cb85c'
},
yellow:{
fontSize: 50,
color: '#f0ad4e'
},
red: {
fontSize: 50,
color: '#d9534f'
}
});
export default PrioLvl;
style={}
或者,您可以在属性内将多个三元运算符链接在一起。但我认为上述方法更容易阅读。
推荐阅读
- javascript - 用于 php 循环的 Javascript 函数
- html - 重定向到表单失败并出现错误 HTTP 404。您正在寻找的资源
- c# - 线程/进程阻塞未按预期工作
- regex - 正则表达式:在有界组内匹配
- c# - 如何为 RabbitMQ 队列定义初始 DeliveryTag 值?
- python - 我无法在 ALM 12.5x 中打开会话
- nosql - 如何在消息传递数据库中获取最新消息?(重新思考数据库)
- ruby-on-rails - 控制器中的验证表单 ruby on rails
- java - Java 方法重载和包装类
- javascript - React-Native:发布模式下的 JavaScript 正则表达式异常(无效组)