React Styled Components 条件三元运算符

React Styled Components conditional ternary operator

我正在尝试根据我的测试值有条件地设置具有三种不同颜色的框的样式。

if test = A or B, it needs to be yellow
if test = C, it needs to be green,
if test = anything else, it needs to be blue.

我宁愿写一个开关或 if/else,但我不知道是否可以不使用带样式组件的三元运算符。

props => ... 只是一个带有隐式 return 的箭头函数,所以你可以给箭头函数一个主体并用 if/else 语句完成你想要的.

您可以使用 props.data && props.data.test 来确保在尝试访问 test 之前设置 props.data

color: ${props => {
  const test = props.data && props.data.test;

  if (test === 'A' || test === 'B') {
    return 'yellow';
  } else if (test === 'C') {
    return 'green';
  } else {
    return 'blue';
  }
}};