如何不使用Bootstrap重构基于react-bootstrap的React JS代码?
无Bootstrap依赖的重构实现
核心思路
- 用原生
ul、li标签替代ListGroup、ListGroup.Item组件 - 选中态(对应原
active属性)通过动态类名绑定实现,完全自己控制样式 - 无需引入任何第三方UI库,所有效果通过自定义CSS实现
重构后的代码
React组件部分
<ul className="custom-list-group"> {car.manufacturers.map(manufacturer => ( <li style={{cursor: "pointer"}} // 此处修正原代码的key错误:遍历项需用自身唯一id作为key,避免渲染异常 key={manufacturer.id} // 动态绑定active类:当前项为选中项时添加active类 className={`custom-list-item ${manufacturer.id === car.selectedManufacturer.id ? 'active' : ''}`} onClick={() => car.SetSelectedManufacturer(manufacturer)} > {manufacturer.name} </li> ))} </ul>
配套自定义CSS
以下是模拟Bootstrap默认列表组样式的实现,你可以根据设计需求任意修改样式:
/* 列表容器样式 */ .custom-list-group { display: flex; flex-direction: column; padding-left: 0; margin: 0; border-radius: 4px; width: 100%; max-width: 400px; /* 可自定义宽度 */ } /* 列表项基础样式 */ .custom-list-item { padding: 8px 16px; color: #333; background: #fff; border: 1px solid #e5e7eb; list-style: none; } /* 处理边框和圆角 */ .custom-list-item:first-child { border-top-left-radius: 4px; border-top-right-radius: 4px; } .custom-list-item:last-child { border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; } .custom-list-item:not(:first-child) { border-top: none; } /* 选中态样式,对应原active属性效果 */ .custom-list-item.active { color: #fff; background: #1677ff; border-color: #1677ff; } /* hover效果(可选) */ .custom-list-item:hover:not(.active) { background: #f5f7fa; }
active实现逻辑说明
react-bootstrap里的active属性本质是组件内部做了判断:当传入的active为true时,自动给DOM元素加上Bootstrap预定义的active类名。我们自己实现就是把这个逻辑拿到组件里手动处理:
- 提前写好
active类对应的选中样式 - 渲染每个列表项时,判断当前制造商id和已选中的制造商id是否匹配
- 匹配就给当前
li添加active类,否则不添加,就能实现完全一致的选中效果
内容的提问来源于stack exchange,提问作者Grande amore
相关产品推荐
相关产品推荐

