需求:如下图所示,根据不同的状态,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;
}
}
}