首页 > 解决方案 > 我如何对道具值进行多次检查以更改该值的颜色。在 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;

标签: reactjsreact-native

解决方案


您可以将逻辑分解为辅助方法:

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={}或者,您可以在属性内将多个三元运算符链接在一起。但我认为上述方法更容易阅读。


推荐阅读