javascript - 为数据分配颜色

标签 javascript reactjs react-native non-repetitive

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

例如我有这个:

  • 如果 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/

相关文章:

reactjs - 覆盖 MUI 芯片删除图标颜色

javascript - 如何保持组件在后台运行以使用react?

react-native - 有没有人在 react native 项目中成功使用 azure-storage 进行 blob 存储?

javascript - FlatList react native : How i can focus scroll in the specific list item

android - 在现有项目React-Native中添加现有原生项目Android

javascript - 将用户输入 (ul) 存储在待办事项列表中,以便在重新打开程序时显示该列表

javascript - 使用 PHP 和 AngularJS 加载更多评论

javascript - Electron Create React App 在构建后未加载

javascript - 如何使用element.offsetBottom?

javascript - 我如何使用 jQuery 在表单中显示更多选项?