使用三元运算符在 React js 的 >2 条件下进行内联样式

Using a ternary operator for inline styling with >2 conditions with React js

我有一个要映射的数据数组,我想根据数组中每个对象的两个项目的比较,将卡片元素设置为三种颜色之一。代码看起来像这样:

data.map(item => {
 return (
  //some code
  <Card className={
   item.someNumber > item.anotherNumber*1.05 ?
   classes.orange :
   item.someNumber < item.anotherNumber*.95 ?
   classes.blue :
   classes.grey}
   >
  //more code

这似乎可行(即我所有的卡片都按预期着色),但我的问题是,这是“错误代码”吗?我真的找不到明确的答案或类似的解决方案(可能我没有问正确的问题);我确实尝试在呈现的代码上方使用 if/else 语句创建函数,但由于我们如何映射数据以及颜色基于数组中每个对象内的比较这一事实,我不能'不知道如何让其他任何东西发挥作用。

您还可以创建一个包含 classNames 逻辑的函数,然后在元素的 className 属性中调用它。参见示例:

const classLogic = () => {
  if (someCondition == true) {
    return "class-1";
  } else {
    return "class-2";
  }
};

<Card className={classLogic()} ></Card>

在这种情况下,我认为归结为偏好和可读性。如果您是唯一一个从事此项目的人,并且您发现嵌套三元组很容易推理,我认为您发布的代码是表达该逻辑的简洁方式。

就我个人而言,我发现嵌套的三元组很难阅读,所以即使需要多写几行代码,我也会找到一种不同的方式来表达该逻辑。

以下是您可能要考虑的一些替代解决方案:

  1. 将选择逻辑移到 props 之外
data.map(item => {
 let className = classes.grey;
 if (item.someNumber > item.anotherNumber*1.05) {
  className = classes.orange;
 } else if (item.someNumber < item.anotherNumber*.95) {
  className = classes.blue;
 }

 return (
  //some code
  <Card className={className}>
  //more code
})
  1. 将选择逻辑移至函数
const getClassName = item => {
 if (item.someNumber > item.anotherNumber*1.05) {
  return classes.orange;
 } else if (item.someNumber < item.anotherNumber*.95) {
  return classes.blue;
 } else {
  return classes.grey;
 }
};

data.map(item => {
 return (
  //some code
  <Card className={getClassName(item)}>
  //more code
})
  1. 在我看来,您列出的 3 个案例可能是相互排斥的(即前两个条件不可能同时为真),在这种情况下,您可以使用像 [=13 这样的辅助库=] 来执行这个逻辑。
import cx from 'classnames';

data.map(item => {
 const className = {
  [classes.orange]: item.someNumber > item.anotherNumber*1.05,
  [classes.blue]: item.someNumber < item.anotherNumber*.95,
  [classes.grey]: item.someNumber >= item.anotherNumber*.95 && item.someNumber <= item.anotherNumber*1.05
 };

 return (
  //some code
  <Card className={cx(className)}>
  //more code
})

由您决定其中任何一个是否比您当前拥有的“更好”或更具可读性。如果您与队友一起工作,我也会征求他们的意见,因为你们都将努力维护相同的代码。

我使用这个库有条件地将 classNames 连接在一起 https://github.com/JedWatson/classnames。使用这个你可以摆脱样板代码(如果你创建另一个函数 returns className),你只需要关注条件和 className。