项目的 API 完成后,Flatlist 将显示绿色勾号

问题描述 投票:0回答:1

我正在创建一个平面列表,我需要在每个项目点击时提交一个带有一些请求选项的 API。成功的 API 响应后,我必须为该特定的平面列表项显示一个绿色勾号。

渲染项目

  const Item = ({item, onPress, backgroundColor, textColor}) => (
  <TouchableOpacity onPress={onPress} style={backgroundColor}>
    <View style={{flexDirection: 'row', width: '100%'}}>
      <Text style={textColor}>{item?.name}</Text>

      <Image
        source={Images.greenTick}
        style={{
          width: 20,
          height: 20,
        }}></Image>
    </View>
  </TouchableOpacity>
);

在这里,我不确定如何在API成功后在特定索引或多个索引上一一管理要在renderItem中显示的图像。预先感谢。

react-native react-native-flatlist
1个回答
0
投票

我认为您必须首先通过维护状态来跟踪单击的项目。我在我的应用程序中尝试过一次。您可以参考下面的示例代码

import React, { useState } from 'react';
import { View, Text, TouchableOpacity, FlatList, Image } from 'react-native';
import Images from './Images'; // Assume this is your images import

const MyListComponent = () => {
  const [data, setData] = useState([...]); // your data array
  const [completedItems, setCompletedItems] = useState([]);

  const handleItemPress = async (item) => {
    // Call your API here
    try {
      await submitApiCall(item);
      // If API call is successful, add item ID to completedItems state
      setCompletedItems((prevItems) => [...prevItems, item.id]);
    } catch (error) {
      console.error('API call failed:', error);
    }
  };

  const renderItem = ({ item }) => (
    <Item
      item={item}
      onPress={() => handleItemPress(item)}
      backgroundColor={{ backgroundColor: '#f9c2ff' }}
      textColor={{ color: 'black' }}
      isCompleted={completedItems.includes(item.id)} // Pass a prop to determine if the item is completed
    />
  );

  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={(item) => item.id.toString()}
    />
  );
};

const Item = ({ item, onPress, backgroundColor, textColor, isCompleted }) => (
  <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
    <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
      <Text style={[styles.title, textColor]}>{item?.name}</Text>
      {isCompleted && <Image source={Images.greenTick} style={{ width: 20, height: 20 }} />}
    </View>
  </TouchableOpacity>
);

// Add your styles here
const styles = StyleSheet.create({
  item: {
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
});

export default MyListComponent;
© www.soinside.com 2019 - 2024. All rights reserved.