React按钮onClick事件中active类状态异常问题排查
问题分析与解决
问题根源
- 普通变量无法持久化状态:
prevClickedBtn是组件内的普通变量,每次组件因状态更新重新渲染时,它都会被重置为null,导致无法正确移除上一个按钮的active类。 - 事件目标不准确:点击按钮时,
event.target可能指向按钮内部的<i>图标或文本节点,而非按钮本身,这会导致获取的id/name错误,进而错误地给无关元素添加active类。 - 直接操作DOM违背React理念:手动通过
classList修改DOM类名,容易造成React状态与实际DOM不同步,引发异常。
修复后的代码
import React from 'react' export default function CourseSection() { const [tab, setTab] = React.useState(null); const sectionBtns = [ { id: 1, name: 'Video', icon_class: 'fa-solid fa-play', btn_name: 'video' }, { id: 2, name: 'Lab', icon_class: 'fa-solid fa-check', btn_name: 'lab' }, { id: 3, name: 'Note', icon_class: 'fa-regular fa-note-sticky', btn_name: 'note' }, { id: 4, name: 'Chat', icon_class: 'fa-regular fa-comment-dots', btn_name: 'chat' }, ] // 直接传递对应tab索引,避免依赖event.target const handleTabClick = (index) => { setTab(index); } return ( <div className='course_section'> <div className='section_button_container'> {sectionBtns.map(({ id, icon_class, name }, index) => { return ( <div className='course_btns' key={id}> <button type='button' // 根据当前tab值动态添加active类 className={`section_btn ${tab === index ? 'active' : ''}`} onClick={() => handleTabClick(index)} > <i className={icon_class}></i> {name} </button> </div> ); })} </div> <div className='data_container'> {tab === 0 && <> <h1>Video Section</h1> </>} {tab === 1 && <> <h1>Lab Section</h1> </>} {tab === 2 && <> <h1>Note Section</h1> </>} {tab === 3 && <> <h1>Chat Section</h1> </>} </div> </div> ) }
关键改动说明
- 用状态控制active类:通过
tab === index的判断,动态给当前激活的按钮添加active类,完全由React状态驱动视图,避免DOM操作。 - 简化点击事件逻辑:点击时直接传递对应标签页的索引,不再依赖
event.target获取信息,彻底解决事件目标不准确的问题。 - 移除无效的普通变量:删掉
prevClickedBtn和手动DOM操作的代码,让组件逻辑更简洁,符合React的设计模式。
内容的提问来源于stack exchange,提问作者Noah
相关产品推荐
相关产品推荐

