0

我试图在用户点击它后立即更改平面列表项的背景颜色。这里的问题是数组已更新,但该选定项目的背景颜色未更改。

我想要做的是-单击平面列表项后,该行的背景颜色应该会改变,但不会改变。以下是我尝试过的代码。

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity } from 'react-native';
        
        let topData = [
            {
                id: '1',
                Name: 'Daily Oprations',
                selected: false,
            },
            {
                id: '2',
                Name: 'Financials',
                selected: false,
            },
            {
                id: '3',
                Name: 'Sharing',
                selected: false,
            },
            {
                id: '4',
                Name: 'Common Questions',
                selected: false,
            },
        ];
        
        const HelpDetails = () => {
            const [data, setData] = useState([]);
            useEffect(() => {
                setData(topData)
            }, []);
        
            const setSelectedIndex = (index) => {
                topData.map((e, i) => e.selected = (index == i))
                setData(topData)
            }
        
            const renderItem = ({ item, index }) => {
                console.log(item);
                return (
                    <TouchableOpacity onPress={() => setSelectedIndex(index)} style={[item.selected ? styles.greenbg : styles.whitebg, styles.storeInformationView]}>
        
                        <Text style={[item.selected ? styles.whitetext : null, styles.name]}>{item.Name}</Text>
                    </TouchableOpacity>
                );
            };
        
            return (
                <FlatList
                    data={data}
                    renderItem={renderItem}
                />
            );
        };
        
        export default HelpDetails;
        const styles = StyleSheet.create({
            greenbg: {
                backgroundColor: 'green'
            },
            whitebg: {
                backgroundColor: 'white',
            },
            storeInformationView: {
                //backgroundColor: APP_COLOR.GREEN_COLOR,
                borderRadius: 12,
                padding: 18,
                elevation: 15,
                marginHorizontal: 10,
                marginTop: 15,
        
                marginBottom: 17,
            },
            whitetext: {
                color: 'white'
            },
            name: {
                fontSize: 15,
                fontWeight: 'bold',
            },
        })
        
        const DATA = [
            {
                id: '1',
                Name: 'Daily Operations',
                selected: true,
            },
            {
                id: '2',
                Name: 'Financials',
                selected: false,
            },
            {
                id: '3',
                Name: 'Sharing',
                selected: false,
            },
            {
                id: '4',
                Name: 'Common Questions',
                selected: false,
            },
        ];
4

2 回答 2

1

您需要在 上添加条件setSelectedIndex。当您从列表中选择任何项目时,您需要在该选定键上设置 true 并在所有其他键上设置 false

const setSelectedIndex = (id) => {
        
        topData.map((item, index) => {
          
          if (index == id) {
            topData[index].selected = true;
          } else {
            topData[index].selected = false;
          }
        });

    setData([...topData]);
  };

请检查完整的更新代码

import React, { useState, useEffect } from 'react';
    import {
      View,
      Text,
      StyleSheet,
      FlatList,
      TouchableOpacity,
    } from 'react-native';
    
    let topData = [
      {
        id: '1',
        Name: 'Daily Oprations',
        selected: false,
      },
      {
        id: '2',
        Name: 'Financials',
        selected: false,
      },
      {
        id: '3',
        Name: 'Sharing',
        selected: false,
      },
      {
        id: '4',
        Name: 'Common Questions',
        selected: false,
      },
    ];
    
    const HelpDetails = () => {
      const [data, setData] = useState([]);
      useEffect(() => {
        setData(topData);
      }, []);
    
      const setSelectedIndex = (id) => {
        // alert(JSON.stringify(topData))
        topData.map((item, index) => {
          // alert(JSON.stringify(index))
          if (index == id) {
            topData[index].selected = true;
          } else {
            topData[index].selected = false;
          }
          //topData[index].selected=true
        });
    
        setData([...topData]);
      };
    
      const renderItem = ({ item, index }) => {
        console.log(item);
        return (
          <TouchableOpacity
            onPress={() => setSelectedIndex(index)}
            style={[
              item.selected ? styles.greenbg : styles.whitebg,
              styles.storeInformationView,
            ]}>
            <Text style={[item.selected ? styles.whitetext : styles.name]}>
              {item.Name}
            </Text>
          </TouchableOpacity>
        );
      };
    
      return <FlatList data={data} renderItem={renderItem} />;
    };
    
    export default HelpDetails;
    const styles = StyleSheet.create({
      greenbg: {
        backgroundColor: 'green',
      },
      whitebg: {
        backgroundColor: 'white',
      },
      storeInformationView: {
        //backgroundColor: APP_COLOR.GREEN_COLOR,
        borderRadius: 12,
        padding: 18,
        elevation: 15,
        marginHorizontal: 10,
        marginTop: 15,
    
        marginBottom: 17,
      },
      whitetext: {
        color: 'white',
        fontWeight: 'bold',
      },
      name: {
        fontSize: 15,
        color: 'black',
        fontWeight: 'bold',
      },
    });

https://snack.expo.io/@vishal7008/flat-list-selection-issue

于 2021-01-27T12:13:09.567 回答
0

我使用 TouchableOpacity 然后添加 onPress 事件并将 FaltList item.id 传递给 onPress 事件。

   import {View, FlatList, Text, TouchableOpacity} from 'react-native';
     
const setSelectedIndex = (id) => {
        topData.map((item, index) => {
          if (index == id) {
            topData[index].selected = true;
          } else {
            topData[index].selected = false;
          }
        });
    
        setData([...topData]);
      };
    render() {
    
      return (
    
          <FlatList style={styles.list}
    
              data={this.state.data}
    
              renderItem={({item}) => (
    
                  <TouchableOpacity onPress={ () => this.actionOnRow(item.id)}>
    
                      <View>
                         <Text>ID: {item.id}</Text>
                         <Text>Title: {item.title}</Text>
                      </View>
    
                 </TouchableOpacity>
    
             )}
          /> 
       );
    }
    
    actionOnRow(item) {
       console.log('Selected Item :',item , item + item.id);
    }

按项目 ID 对项目执行操作

于 2021-01-27T11:43:44.887 回答