1

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

例如我有这个:

  • 如果value :'high'文本颜色应该是red.

  • 如果value :'low'文本颜色应该是green.

  • ETC....

这是我的代码,但我必须将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>
        )
  }
}

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

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

任何建议表示赞赏。谢谢!

4

1 回答 1

2

您可以有一个对象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>;
  }
}
于 2018-08-09T18:05:57.163 回答