使用 Map 方法反應原生串列
我想要實作的是,當單擊專案時,我希望在 Selected 專案下方添加一個新專案(我更喜歡添加一個新的自定義視圖)。
世博小吃代碼>
uj5u.com熱心網友回復:
由于您正在更改所選專案的背景,因此有必要更新串列中每個專案的 ID,否則插入元素會破壞此功能。此外,您需要為 for 添加一個狀態,否則您無法觸發 UI 更改
您可以按如下方式實作所需的行為。
const [selectedId, setSelectedId] = useState(null); const [data, setData] = React.useState(persons) function handleOnPress(idx) { setSelectedId(idx) const first = data.slice(0, idx 1); const second = data.slice(idx 1).map(p => ({...p, id: Number(p.id) 1})); setData([...first, {id: idx 2, name: "Whatever new iten"}, ...second]) } return ( <View style={styles.container}> <ScrollView> <View> {data.map((person, index) => { const backgroundColor = index === selectedId ? "#6e3b6e" : "#f9c2ff"; return ( <TouchableOpacity onPress={() => handleOnPress(index)} style={{ padding:20, backgroundColor: backgroundColor, marginBottom:20, }} > <Text>{person.name}</Text> </TouchableOpacity> ); })} </View> </ScrollView> </View> );
用于
slice
將陣列拆分為兩部分。用于map
更新id
第二個陣列中元素的屬性。最后,合并這兩個部分,但在它們之間插入一個新元素。這是一個更新的小吃。
uj5u.com熱心網友回復:
在提供解決方案的想法之前,有一些要點需要考慮,我會在這里列出:
- React Native 提供了性能優化的組件來處理名為
<FlatList />
/的串列渲染<SectionList />
。使用這些組件而不是.map()
渲染組件串列- 您需要為要更改的串列創建一個內部狀態
- 使用或其他 Array 方法渲染組件串列時需要提供一個
key
道具.map()
只需對您提供的代碼進行最少的更改,您就可以創建一個狀態來存盤串列,并且當按下該專案時,您可以在此串列中插入一個新專案:
import React, { useState } from "react"; import { Text, View, StyleSheet, ScrollView, TouchableOpacity } from 'react-native'; const people = [/* your list */]; export default function App() { const [peopleList, setPeopleList] = useState(people) const [selectedId, setSelectedId] = useState(null); return ( <View style={styles.container}> <ScrollView> <View> {list.map((person, index) => { return ( <TouchableOpacity onPress={() => { setSelectedId(person.id) const newPerson = {...person}; // The new item setPeopleList((prevList) => [...prevList.slice(0,index 1), newPerson, ...prevList.slice(index 1)]) }} style={{ padding:20, backgroundColor: backgroundColor, marginBottom:20, }} > <Text>{person.name}</Text> </TouchableOpacity> ); })} </View> </ScrollView> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, padding:20 } });
帶有作業代碼的沙箱:https ://snack.expo.dev/5rvTbrEvO
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/531736.html
標籤:反应式
上一篇:如何在這個非常簡單的ReactNative應用程式中存盤資料?
下一篇:任務:react-native-async-storage_async-storage:generateReleaseRFileFAILED