【问题标题】:How do I style a react component based on multiple conditions?如何根据多个条件设置 React 组件的样式?
【发布时间】:2021-01-01 17:16:36
【问题描述】:

我有一份带有有效期的产品清单。我想根据我的商品是今天到期、今天不到期还是已经到期来应用样式。(我可能需要处理更多条件)。
我已经成功地使用嵌套三元运算符或使用带有三元运算符的样式数组来做到这一点,如下所示。

 <ListItem  
     containerStyle={
          [exp_check === -1 ? { backgroundColor: '#ff9ea5' } : null,
                exp_check === 0 ? { backgroundColor: '#fff185' } : null]
                    }
     badge={
          exp_check !== 1 ?
               exp_check === -1 ? { status: 'error', value: `!` } : { status: 'warning'} : null
           }
/>

有没有办法为样式或任何其他道具实现类似 switch 声明。我希望能够轻松地有条件地设置我的道具,而无需编写嵌套逻辑或数组。类似于:

stlye / badge / any prop accepted by the component = {
switch(something):
CASE1: ..
CASE2:.. 
etc etc 
CASE N:
}

我不确定是否可以在 prop 中编写 IF/ELSE 语句,因为如果我尝试这样做,我无法编译它。

【问题讨论】:

  • 为什么不在渲染之前计算呢?复杂逻辑属于适合复杂逻辑的地方。
  • 我该怎么做?我想我可以让我的到期检查函数返回一个字符串并使用该字符串访问我的样式表对象,但它仍然感觉很hacky。
  • 在开始渲染之前把它放在代码中?目前尚不清楚最终的问题是什么。
  • 是的,我知道了,我想我只是盯着屏幕太久了。

标签: reactjs react-native conditional-operator conditional-rendering


【解决方案1】:

考虑一种方法,您有一个分类函数,将给定项目分类到特定组,然后将道具或样式或类名映射到组。

const ONE_HOUR = 1000 * 60 * 60;
const ONE_DAY = ONE_HOUR * 24;

// an array of status names/labels, each with a predicate function
// to test whether a given item matches. first match wins.
const bins = [
  {
    status: 'expired',
    predicate: time => time < Date.now(),
  },
  {
    status: 'urgent',
    predicate: time => Date.now() - time < ONE_HOUR
  },
  {
    status: 'soon',
    predicate: time => Date.now() - time < ONE_DAY,
  },
  {
    status: 'normal'
    predicate: () => true
  }
}

// find the first bin whose predicate function returns true for the item and use that bin's 'status'
const expirationStatus = bins.find(bin => bin.predicate(item.expirationTime)).status;

// now expirationStatus is one of 'expired', 'urgent', 'soon', or 'normal'
// which you can then use to assign styles or classNames or whatever:

// these could live in the bins too, as a 'style' or 'className' property or whatever.
const styles = {
  expired: {
    background: 'grey',
  },
  urgent: {
    background: 'red'
  },
  soon: {
    background: 'yellow'
  },
  normal: {
    background: 'green'
  }
}

return (
  <Component
    style={styles[expirationStatus]} {/* this */}
    status={expirationStatus} {/* and/or this */}
    className={expirationStatus} {/* and/or this */}
  />
)

【讨论】:

  • 谢谢我做了类似的事情。
猜你喜欢
  • 1970-01-01
  • 2018-08-26
  • 2022-10-16
  • 2023-04-06
  • 2019-02-07
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多