Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

React native elements Checkbox selecting multiple items using react hooks

I need a little help trying to figure this out. I am using react native elements flatlist with a checkbox inside of it. I am also using react hooks with this. Everything is working perfectly but when I try and select one of the items in the checkbox it selects all of the items. Now I have had this issue before when I was just using components and not hooks and functions. I tried to use the same method that I used here Selecting multiple items

Like this...

function ViewCategoryWS2({navigation}) {
    const {category, setCategory} = useContext(ItemContext);
    const [eats, setEats] = useState([]);
    const [checked, toggleChecked] = useState(false); 
   
    function back() {
        navigation.navigate('MenuWS2');
    }
    
    function test(index) {
        const foods = category;
        foods[index].checked = !foods[index].checked;
        setCategory(foods);

    }
  
    return (
        
        <View style={styles.container}>
            
         
            <Icon 
                name='arrow-left'
                color="#000000"
                size={25}
                style={styles.menuIcon}
                onPress={back}
            />
          
            <FlatList
                data={category}
                //extraData={eats}
                keyExtractor={(item, index) => index.toString()}
                renderItem={({ item, index }) => (
                    <CheckBox 
                        center 
                        titleProps={{ color: 'black', fontWeight: 'bold'}}
                        title={item}
                        iconRight
                        checked={checked}
                        onPress={() => test(index)}
                        size={30}
                        containerStyle={styles.checkBox} 
                    />  
                    
                )}
            />
     
        
        </View>
       
    )
    

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

App Output:

enter image description here

import React, { useState } from 'react';
import { Text, View, StyleSheet, CheckBox, Icon, FlatList } from 'react-native';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

/*
I am using this data, but you can continue
with the one you getting from context
*/
const data = [
  { id: 1, title: 'one', checked: true },
  { id: 2, title: 'two', checked: false },
  { id: 3, title: 'three', checked: false },
  { id: 4, title: 'four', checked: false },
  { id: 5, title: 'five', checked: false },
  { id: 6, title: 'six', checked: false },
];
export default function App() {
  const [category, setCategory] = useState(data);
  const [eats, setEats] = useState([]);
  const [checked, toggleChecked] = useState(false);

  function back() {
    // navigation.navigate('MenuWS2');
  }

  function test(index) {
    /* 
      Use this approach while changing the state. 
      This will create the copy of original array, 
      and you can perform mutation there 
      and update state with it.
    */
    console.log(index);
    const foods = [...category];
    foods[index].checked = !foods[index].checked;
    setCategory(foods);
  }

  /* 
    In your Checkbox component, 
    use "onChange" prop instead of "onPress" 
    and "value" instead of "checked" 
  */

  return (
    <View style={styles.container}>
      <FlatList
        data={category}
        //extraData={eats}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item, index }) => (
          <Card style={{ padding: 10, margin: 5 }}>
            <Text>{item.title}</Text>
            <CheckBox
              center
              titleProps={{ color: 'black', fontWeight: 'bold' }}
              title={item}
              iconRight
              value={item?.checked}
              onChange={() => test(index)}
              size={30}
              containerStyle={styles.checkBox}
            />
          </Card>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    marginTop: 24,
    backgroundColor: 'grey',
    flex: 1,
  },
});

Working Example: Expo Snack


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...