【问题标题】:i want to show selected numbers in react native我想在本机反应中显示选定的数字
【发布时间】:2022-07-14 19:14:36
【问题描述】:

我创建了一个数字列表,我想在不同的视图中显示选定的项目,但我的代码只显示按下的项目。如果 onPress 被触发,我希望它喜欢视图中的 1 2 3.. 数字

import React,{useState} from "react";
import { FlatList, ScrollView, SafeAreaView, View, StyleSheet, Text, TouchableOpacity } from "react-native";

这是显示数字列表的内容

const Item = ({ item, onPress, onLongPress, backgroundColor, textColor }) => {
  return (
    <TouchableOpacity  onPress={onPress}
      style={[styles.item, backgroundColor]}>
      <Text style={[styles.title, textColor]}>{item.NO}</Text>
    </TouchableOpacity>
  );
}

FLATLIST COMPONENT 显示渲染项

export const FlatListComponent = (item,textColor) => {
  const navigation = useNavigation();
 
  const [numbers, setNumbers] = useState([
    { id: 1, NO: '1' }, { id: 2, NO: '2' }, { id: 3, NO: '3' }, { id: 4, NO: '4' }, { id: 5, NO: '5' },
    { id: 6, NO: '6' }, { id: 7, NO: '7' }, { id: 8, NO: '8' }, { id: 9, NO: '9' }, { id: 10, NO: '10' },
    { id: 11, NO: '11' }, { id: 12, NO: '12' }, { id: 13, NO: '13' }, { id: 14, NO: '14' }, { id: 15, NO: '15' },
    { id: 16, NO: '16' }, { id: 17, NO: '17' }, { id: 18, NO: '18' }, { id: 19, NO: '19' }, { id: 20, NO: '20' },
  ]);

  const [selectedItems, setSelectedItems] = useState([]);  

  const RenderItem = ({ item }) => {
    const backgroundColor = item.NO === selectedItems? "#6e3b6e" : "#f9c2ff";
    const color = item.NO === selectedItems ? 'white' : 'black';

    return (
      <Item
        item={item}
        backgroundColor={{ backgroundColor }}
        textColor={{ color }}
        onPress={() => setSelectedItems(item.NO)}
      />
    );
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={{ flexDirection: "row", flexWrap: "wrap" }}>
        {numbers.map((item, index) => {
          return (
            <View style={{ width: '20%', flexDirection: "row" }}>
              <RenderItem
                keyExtractor={item.id}
                item={item}
                extraData={selectedItems}
              />
            </View>
          )
        }
        )}
        <View >

          <Text>{selectedItems}</Text></View>
      </ScrollView>
    </SafeAreaView>
  );
};

【问题讨论】:

    标签: react-native function state hook touchableopacity


    【解决方案1】:
    const [selectedList , setSelectedList] = useState([])
    

    将选中的项推入 selectedList 数组 =>

             if (!selectedList?.includes(item.id)){
    
                    selectedList.push(item.no);
    
                    setSelectedList(selectedList)
    
                }
    

    并查看 selectedList。

    【讨论】:

      猜你喜欢
      • 2019-11-05
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2021-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多