React中如何修改map函数返回的特定组件的样式实现单选高亮?
问题根源
你当前的实现中,每个<UserList>组件单独维护了内部的isClicked状态,各个组件的状态互相独立,所以点击多个按钮后所有被点击过的都会保持紫色选中态。要实现单选效果,需要把选中状态提升到多个<UserList>的公共父组件中统一管理。
修改方案
- 父组件新增选中状态管理,将选中标识、选中回调通过props传给子组件:
// 父组件代码 const ParentComponent = () => { // 存储当前选中项的索引,初始为null代表无选中 const [activeIndex, setActiveIndex] = useState(null); return ( <div> {TestData.map((data, index) => ( <UserList data={data} key={index} isActive={activeIndex === index} onSelect={() => setActiveIndex(index)} /> ))} </div> ) }
- 调整
<UserList>子组件,移除内部状态,改用父组件传入的props判断选中态:
const UserList = ({ data, isActive, onSelect }) => { return ( <UserDiv style={{ border: isActive ? color.click : '你原本的灰色边框值' }} onClick={onSelect} > <b>{data.name}</b> <br /> <InfoText> {data.company} / {data.position} </InfoText> </UserDiv> ); };
优化提示
如果你的TestData中的每一项有唯一业务ID(比如用户ID),推荐用唯一ID代替数组索引作为选中标识,避免数组排序、增删后出现选中状态错乱的问题。
内容的提问来源于stack exchange,提问作者Yumin Lee
相关产品推荐
相关产品推荐

