React Native中如何实现ListItem.Accordion单条项独立展开?
解决React Native Elements ListItem.Accordion批量展开问题
你的问题根源在于用了单个布尔值expanded控制所有折叠项的展开状态,点击任何一项都会触发全局状态变化,导致所有项同步展开/收起。要实现仅展开选中项,只需把状态改成记录当前展开项的索引即可,具体修改步骤如下:
- 替换状态变量
把原来的布尔值状态换成记录索引的状态:
// 原代码 const [expanded, setExpanded] = useState(false); // 修改为 const [expandedIndex, setExpandedIndex] = useState(null); // null表示无展开项
- 更新ListItem.Accordion的属性
调整isExpanded和onPress的逻辑,绑定当前项的索引:
<ListItem.Accordion // 其他属性保持不变 isExpanded={expandedIndex === index} // 仅当前索引匹配时展开 onPress={() => { // 点击已展开的项则收起,否则展开该项 setExpandedIndex(expandedIndex === index ? null : index); }} > {/* 子内容保持不变 */} </ListItem.Accordion>
修改后的完整代码示例
{meals.map((item, index) => { return ( <ListItem.Accordion theme={{ colors: { primary: "#4169e1" } }} style={tw`px-3 rounded py-3 text-white`} containerStyle={{ backgroundColor: "#000000", borderRadius: "10px" }} content={ <> <Text style={tw`text-5xl mr-2`}>☀️</Text> <ListItem.Content> <ListItem.Title style={tw`font-bold text-white`}>{item.title}</ListItem.Title> <Text style={tw`text-white`}>480 calories</Text> </ListItem.Content> </> } key={index} index={index} noRotation isExpanded={expandedIndex === index} icon={ <Icon style={tw`mt-3 p-2`} size={35} name="add-circle-outline" color="white" type="material" /> } onPress={() => { setExpandedIndex(expandedIndex === index ? null : index); }} > <ListItem containerStyle={{ backgroundColor: "#000000", borderRadius: "10px" }} style={tw`px-3 mt-[-25]`} onPress={() => console.log("hi")} bottomDivider > <ListItem.Content> <ListItem.Title> <Divider width={1} style={tw`w-full`} /> <View style={tw`justify-around items-center flex-row w-full`}> <View> <Text style={tw`text-gray-400`}>Fats</Text> <Text style={tw`font-bold text-white`}>28.4</Text> </View> <View> <Text style={tw`text-gray-400`}>Carbs</Text> <Text style={tw`font-bold text-white`}>42.32</Text> </View> <View> <Text style={tw`text-gray-400`}>Prot</Text> <Text style={tw`font-bold text-white`}>60,45</Text> </View> <View> <Text style={tw`text-gray-400`}>RDC</Text> <Text style={tw`font-bold text-white`}>12%</Text> </View> </View> </ListItem.Title> <ListItem.Subtitle style={tw`p-2`}> <View style={tw`py-3`}> <View style={tw`flex-row py-5 items-center justify-between w-full`} > <View style={tw`flex-row ml-2`}> <Icon name="restaurant-menu" size={50} color="white" type="material" /> <View style={tw`ml-3 justify-center`}> <Text style={tw`font-bold text-white`}>Pepperoni Sandwich</Text> <Text style={tw`text-white`}>2 pieces</Text> </View> </View> <Icon name="edit" size={30} color="white" type="material" /> </View> </View> </ListItem.Subtitle> </ListItem.Content> </ListItem> </ListItem.Accordion> ) })} </View> ); };
内容的提问来源于stack exchange,提问作者reactLover
相关产品推荐
相关产品推荐

