【问题标题】:Assigning colors to data为数据分配颜色
【发布时间】:2018-08-09 18:02:03
【问题描述】:

有没有一种有效的方法可以通过考虑传递的值来为元素分配颜色,而无需对每个组件重复代码?

例如我有这个:

  • 如果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>
        )
  }
}

这很好用,但我在很多组件中都有这个。

如果这是最好的解决方案,而且不会变得复杂,我对此感到满意,因为它只是重复和额外的行。

感谢任何建议。谢谢!

【问题讨论】:

    标签: javascript reactjs react-native non-repetitive


    【解决方案1】:

    您可以有一个对象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>;
      }
    }
    

    【讨论】:

    • 你很有帮助,再次感谢。我没有想到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2013-03-26
    • 2021-06-25
    • 2016-05-14
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    相关资源
    最近更新 更多