如何在React中为色块图片添加hover和点击选中后的常驻边框效果
你已经用currentSelection状态存储了当前选中的值,只需要新增选中态样式,再给选中的色块动态绑定对应类名即可实现点击后常驻边框的效果,具体修改如下:
1. 修改CSS样式
新增选中态的边框规则,为了避免边框出现时撑大元素导致页面位移,提前预留透明边框的位置:
.text-image-list-image { height: 40px; width: 40px; border-radius: 4px; margin-left: 15px; margin-right: 15px; /* 提前预留边框位置,避免选中时元素位移 */ border: 2px solid transparent; box-sizing: border-box; } /* 新增选中态样式,边框色可自行调整 */ .text-image-list-image.selected { border-color: #2563eb; } .text-image-list-title { margin-bottom: 6px !important; }
2. 修改JSX渲染逻辑
遍历色块时判断当前项的value是否和已选中的currentSelection相等,匹配成功就添加选中类:
return ( <div> <Title name={name} /> {content.map(({ src, content, value }, index) => ( <div key={index} style={{ display: "inline-block", cursor: "pointer"}} onClick={ () => setCurrentSelection(value)}> <p>{content}</p> <a> <img className={`text-image-list-image ${currentSelection === value ? 'selected' : ''}`} src={src} alt="" /> </a> </div> ))} </div> );
你预期的效果参考:
未选中状态:
选中后常驻边框状态:
补充说明:如果你的
value是对象、数组这类引用类型,建议用唯一ID作为匹配判断条件,避免选中状态匹配失败。如果不需要预留边框位置,也可以把边框替换为outline属性,不会占据元素空间,写法为outline: 2px solid #2563eb; outline-offset: 2px;,可调整outline-offset控制边框和色块的间距。
内容的提问来源于stack exchange,提问作者Dave Smith
相关产品推荐
相关产品推荐

