React Native中如何实现点击数组项单独切换折叠图标?
解决折叠组件单个项图标独立切换的问题
问题根源在于你用了单个全局状态iconName,所有折叠项都绑定这个状态,所以点击任何一项都会触发全局状态更新,导致所有图标同步变化。要实现单个项独立切换,需要给每个项维护自己的展开状态。
修改方案
- 将状态改为记录每个项的展开状态(比如用数组存储展开项的索引)
- 点击时仅更新当前项的状态
- 根据每个项的状态单独渲染对应图标
修改后的代码
import React, { useState } from 'react'; // 导入你的其他组件和样式... const YourComponent = () => { // 用数组记录展开项的索引,初始为空(所有项折叠) const [expandedIndices, setExpandedIndices] = useState([]); // 判断指定索引的项是否展开 const isItemExpanded = (index) => expandedIndices.includes(index); // 切换指定项的展开状态 const toggleItemExpand = (index) => { setExpandedIndices(prevState => { if (prevState.includes(index)) { // 若已展开,移除索引,变为折叠 return prevState.filter(i => i !== index); } else { // 若未展开,添加索引,变为展开 return [...prevState, index]; } }); }; return ( <AppScreen> <ScrollView style={styles.container}> {terms.map((term, index) => { const isExpanded = isItemExpanded(index); return ( <Collapse key={index} style={styles.overlayContainer} onToggle={() => toggleItemExpand(index)} > <CollapseHeader style={styles.collapseHeaderStyle}> <View style={styles.collapseHeaderStyle}> <AppText style={styles.title}>{term.title}</AppText> </View> <AppIcon iconName={isExpanded ? "chevron-up" : "chevron-down"} iconType="ionicon" iconColor={colors.secondary} /> </CollapseHeader> <CollapseBody style={styles.collapseBody}> {term.contents.map((content, contentIndex) => ( <React.Fragment key={contentIndex}> <AppText style={styles.content}>{content.content}</AppText> </React.Fragment> ))} </CollapseBody> </Collapse> ); })} </ScrollView> </AppScreen> ); }; export default YourComponent;
关键修改点
- 用
expandedIndices数组替代单个iconName状态,精准记录每个项的展开状态 toggleItemExpand函数只更新当前点击项的索引,不影响其他项- 每个折叠项根据自身索引的状态独立渲染图标
- 优化了内部
contents的遍历方式(直接用term.contents而非terms[index].contents),同时给内部遍历的key换为contentIndex,避免与外层索引冲突
内容的提问来源于stack exchange,提问作者serking
相关产品推荐
相关产品推荐

