反应原生元素复选框使用反应钩子选择多个项目

如何解决反应原生元素复选框使用反应钩子选择多个项目

我需要一点帮助来解决这个问题。我正在使用 React Native Elements flatlist,里面有一个复选框。我也在使用反应钩子。一切正常,但是当我尝试选择复选框中的项目之一时,它会选择所有项目。现在,当我只使用组件而不是钩子和函数时,我就遇到过这个问题。我尝试使用我在此处使用的相同方法 Selecting multiple items

像这样...

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>
       
    )
    

}

并且我不断收到此错误 TypeError: Attempted to assign to readonly property。我也试过这种方式...

         <FlatList
                data={category}
                //exTradata={eats}
                keyExtractor={(item,fontWeight: 'bold'}}
                        title={item}
                        iconRight
                        checked={checked}
                        onPress={() => toggleChecked(!checked)}
                        size={30}
                        containerStyle={styles.checkBox} 
                    />  
                    
                )}
            />

这是我的代码来自上下文的来源。这个页面我从我的数据库提取数据并显示类别。我点击任何类别,它从我的数据库提取数据,这些数据分配给点击的特定类别..

这是代码...

import ItemContext from '../context/CategoryItems';

export default function menuWS({navigation}) {
    const [restaurantlocationcode,setRestaurantlocationcode] = useState('')
    const [menu,setMenu] = useState([]);
    const {category,setCategory} = useContext(ItemContext);
    const [selected,setSelected] = useState(0);

    function viewMenu() {
        fetch('URL',{
            method: 'POST',body: JSON.stringify({ restaurantlocationcode: restaurantlocationcode}),headers: {
                'Accept': 'application/json','Content-Type': 'application/json',},})
        .then(response => response.json())
        .then(response=> setMenu(response));
        console.log(menu);
        alert(menu);

    }
    
    function viewCategory({item}) {
        fetch('URL',body: JSON.stringify({
                category: item,restaurantlocationcode: restaurantlocationcode,}),})
        .then(response => response.json())
        .then(response => {
            setCategory(response);
            console.log(response);
            alert(response);
        });
        navigation.navigate('ViewCategoryWS2',{category});
        
    }

    function showMenu() {
        console.log(menu);
        alert(menu);
    }

    
    const buttons = ['Menu']

    return (
        
        <View style={styles.container}>
            <Input
                style={styles.Input} 
                placeholder='Restaurant Location Code'
                leftIcon={
                    <Icon
                    name='location-arrow' 
                    size={24}
                    color='black'
                    />
                }
                onChangeText={setRestaurantlocationcode}
                value={restaurantlocationcode}
                underlineColorAndroid='transparent'
            />

            <ButtonGroup
                onPress={viewMenu}
                selectedindex={selected}
                selectedButtonStyle={{backgroundColor: 'blue'}}
                buttons={buttons}
                containerStyle={styles.buttonGroup} 
            />


            <FlatList 
                data={menu}
                exTradata={category}
                keyExtractor={(item,index) => index.toString()}
                renderItem={({item,index}) => (
                    <ListItem
                    titleStyle={{ color: 'black',fontWeight: 'bold'}}
                    title={item}
                    onPress={() => viewCategory({item})}
                    bottomDivider
                    chevron
                    />
                )}
            />
        
        </View>
        
    )

}

这是我的 useContext 代码...

import { createContext } from 'react';

const ItemContext = createContext({});

export default ItemContext;

这是我的 useContext 代码的第二部分..

import React,{useState} from 'react';
import ItemContext from './CategoryItems';

const MenuItemState = ({children}) => {
    const [category,setCategory] = useState([]);
    return (
        <ItemContext.Provider value={{category,setCategory}}>

            {children}
        </ItemContext.Provider>
    )
}

export default MenuItemState;

它只选择所有项目。我不确定我错过了什么。不胜感激。

解决方法

应用输出:

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',{ id: 4,title: 'four',{ id: 5,title: 'five',{ id: 6,title: 'six',];
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,},});

工作示例:Expo Snack

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?