[React] 纯SCSS实现一个checkbox

需求:如下图所示,根据不同的状态,Status这一列显示不同的样式,如果状态是In Progress,则显示橘色的线框;如果状态是Complete,则显示蓝色背景加对勾的框,类似于checkbox

一开始笔者对于蓝色背景加对勾的框用的是Input checkbox来实现的,但这样会有一个问题,就是Input的onChange事件会去执行两次,这样导致页面显示不稳定(什么原因导致的,笔者有待继续去研究,如果弄明白了,会在此更新)

一开始的写法如下:

<div className="checkboxOne">
    <label className="status_label">
        {
            ['In Progress'].includes(record.status) ? (
                <div 
                    className="border_outline"
                    onClick={(e)=>{
                        console.log("1::record:", record);
                        changeStatus(e, record)}
                    }
                />
            ) : (
                <input
                   className="status_style"
                   type="checkbox"
                   id={record.index}
                   name={record.status}
                   checked
                   onChange={(e) => {
                     console.log("2::record:", record);
                     changeStatus(e, record);
                   }}
                  />
            )

        }
    </label>
</div>

这样导致的一个问题是:点击橘色线框的时候,本来应该只打印“1::record:”这一行,但是下面用的Input checkbox中的onChange事件也被执行了,所以在点击橘色线框的时候同时打印了"1::record:"和“2::record:”, 也就是changeStatus这个方法在点击一次的时候执行了两次

 

解决办法:把Input checkbox改为用div来显示,然后通过样式来实现checkbox的样式显示

部分主要代码如下:

<div className="checkboxOne">
    <label className="status_label">
        {
            ['In Progress'].includes(record.status) ? (
                <div 
                    className="border_outline"
                    onClick={(e)=>{changeStatus(e, record)}}
                />
            ) : (
                <div className="status_style"
                    onClick={(e)=>{changeStatus(e, record)}}
                >
                    <div className="status_yes"/>
                </div>
            )

        }
    </label>
</div>

SCSS代码如下:

.checkboxOne {
    display: flex;
    justify-content: center;
    align-items: center;
    &:hover {
      cursor: pointer;
    }
    .status_label {
      height: 1rem;
      &:hover {
        cursor: pointer;
      }

      .border_outline {
         width: 17px;
         height: 17px;
         border: 1px solid #ffb300;
         border-radius: 3px;
      }

      .status_style {
         width: 17px;
         height: 17px;
         background: #269BEE;
         border-radius: 3px;
         position: relative;
      }
      .status_yes {
         border: 2px solid #fff;
         width: 12px;
         height: 8px;
         border-top: none;
         border-right: none;
         transform: rotate(-45deg);
         top: 3px;
         left: 3px;
         position: absolute;
       }
    }
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值