React Native SectionList不同分组如何渲染对应自定义组件
实现方案
核心思路:SectionList 的 renderItem 回调参数自带当前项所属的 section 对象,可通过该对象的唯一标识(如title或自定义的type字段)判断需要渲染的对应组件。
步骤1:修正并完善DATA结构
先修正你原DATA数组的语法错误,同时可给每个分组新增自定义renderType字段(可选,直接用title判断也可,新增字段可避免后续标题修改影响渲染逻辑):
const DATA = [ { title: "Groups", renderType: "group", // 自定义的渲染类型标识 data: [ { groupName: "Samwise", }, ], }, { title: "Noters", renderType: "noter", data: [ // 你原代码此处漏了data字段声明,已修正 { userName: "Merri", }, ], }, { title: "Contacts", renderType: "contact", data: termIsContact.length ? termIsContact : contacts, }]
步骤2:实现各分组对应的列表项组件
分别为三类分组写对应的渲染组件,你已有的联系人组件可以直接复用:
// 分组项组件 const GroupItem = ({ groupName }) => ( <View style={/* 自定义样式 */}> <Text>{groupName}</Text> </View> ) // 备注者项组件 const NoterItem = ({ userName }) => ( <View style={/* 自定义样式 */}> <Text>{userName}</Text> </View> ) // 原有联系人项组件 const ContactItem = ({ givenName, familyName }) => ( <TouchableOpacity onPress={() => toggleContact(`${givenName} ${familyName}`)} style={tw.style("justify-start pl-4 w-full flex flex-row items-center", { height: 56, borderBottomColor: "#aaaaaa", borderBottomWidth: 1, })} > <Avatar name={`${givenName} ${familyName}`} size={32} backgroundColor={"#D9F3FC"} labelColor={"#16ade0"} /> <Text style={tw.style("text-black text-base pl-2", {})}> {givenName} {familyName} </Text> </TouchableOpacity> )
步骤3:改造renderItem逻辑
根据section的标识返回对应组件:
const renderItem = ({ item, section }) => { switch(section.renderType) { case 'group': return <GroupItem groupName={item.groupName} /> case 'noter': return <NoterItem userName={item.userName} /> case 'contact': return <ContactItem familyName={item.familyName} givenName={item.givenName} /> default: return null } }
如果你不想加renderType字段,直接把switch的判断条件换成section.title也可以,对应匹配"Groups"、"Noters"、"Contacts"即可。
步骤4:保持SectionList调用不变
你原来的SectionList代码不需要修改,直接使用改造后的renderItem即可运行。
内容的提问来源于stack exchange,提问作者kinzito17
相关产品推荐
相关产品推荐

