微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何根据多个条件设置反应组件的样式?

如何解决如何根据多个条件设置反应组件的样式?

我有一个产品列表及其有效期。我想根据样式是今天要过期,今天不过期还是已经过期来应用样式。(可能还有更多条件要使用)。
我已经成功地使用嵌套三元运算符或使用具有三元运算符的样式数组做到了这一点,如下所示。

 <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语句,因为如果尝试这样做,我将无法使其编译。

解决方法

考虑一种方法,其中您具有将给定项目分类到特定组中,然后将道具或样式或类名映射到这些组上的分类功能。

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 */}
  />
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。