Как я могу выбрать элементы плоского списка и выделить элементы в react-native с помощью функции onPress?

#react-native-android

#react-native

Вопрос:

Я не знаю, как выбрать элементы плоского списка в onPress и отобразить выделение элементов плоского списка в функции onPress с помощью flatlist. В этом плоском списке я извлекаю данные с помощью package.js файл и использование метода класса

Код

 import React from 'react'
import {Stylesheet, View, Text, TouchableOpacity, FlatList, ScrollView } from 'react-native'
import PACKAGE from './Package'

export default class extends React.Component {
 constructor(props) {
    super(props)
    this.state = {
      selected: '',
    }
 
 _OnPress =() =>{
 /**/ 
 }

 <FlatList
          data={PACKAGE}
          contentContainerStyle={{ paddingRight: 20 }}
          horizontal
          showsHorizontalScrollIndicator={false}
          renderItem={({ item, separators }) => (
            <View style={{ paddingLeft: 20 }}>
              <TouchableOpacity style={[styles.myAccountPriceInfo, { backgroundColor: item.color }]}>
                <View>
                  <Text style={[styles.priceText, { color: item.textColor }]}>{item.name}</Text>
                </View>
                <View style={styles.priceDetail}>
                  <Text style={[styles.numText, { color: item.textColor }]}>from </Text>
                  <Text style={[styles.dollarText, { color: item.textColor }]}>$</Text>
                  <Text style={[styles.priceNumText, { color: item.textColor }]}>{item.cost}</Text>
                </View>
              </TouchableOpacity>
            </View>
          )}
        />
}
  

Комментарии:

1. где вы хотите отобразить элемент выделения?

2. Я хочу выделить элементы, доступные для касания, в flatlist. Например, когда пользователь выбирает элемент в плоском списке, они могут видеть, что элемент был выбран. Итак, не могли бы вы помочь этому запросу и большое вам спасибо за ваш ответ.

3. Может ли пользователь выбрать несколько элементов или только один?

4. можете ли вы также привести пример структуры данных пакета?

5. Пользователь может выбирать только один элемент за раз.

Ответ №1:

Вы могли бы использовать _OnPress функцию следующим образом.

 import React from 'react'
import {Stylesheet, View, Text, TouchableOpacity, FlatList, ScrollView } from 'react-native'
import PACKAGE from './Package'

export default class extends React.Component {
 constructor(props) {
    super(props)
    this.state = {
      selected: null,
    }

 renderItem = ({ item, separators }) => {
   // you can know here whether the item is selected or not.
   const isSelected = item.name === this.selected.selectedItem;

   return ( 
      <View style={{ paddingLeft: 20 }}>
        <TouchableOpacity 
          style={[
            styles.myAccountPriceInfo, { backgroundColor: item.color },
            // you could highlight your selected item like this.
            isSelected amp;amp; styles.highlightSelected
          ]}
          // let the state know which item has been selected
          onPress={() => this.setState(item.name)}
        >
          <View>
            <Text style={[styles.priceText, { color: item.textColor }]}>{item.name}</Text>
          </View>
          <View style={styles.priceDetail}>
            <Text style={[styles.numText, { color: item.textColor }]}>from </Text>
            <Text style={[styles.dollarText, { color: item.textColor }]}>$</Text>
            <Text style={[styles.priceNumText, { color: item.textColor }]}>{item.cost}</Text>
          </View>
      </TouchableOpacity>
    </View>
   )
 }

  return ( 
    <FlatList
      data={PACKAGE}
      contentContainerStyle={{ paddingRight: 20 }}
      horizontal
      showsHorizontalScrollIndicator={false}
      renderItem={renderItem}
    />
  )
}