【问题标题】:React native elements Checkbox selecting multiple items using react hooks反应原生元素复选框使用反应钩子选择多个项目
【发布时间】:2020-12-31 16:43:16
【问题描述】:

我需要一些帮助来解决这个问题。我正在使用带有复选框的反应原生元素平面列表。我也在用这个反应钩子。一切正常,但是当我尝试选择复选框中的一项时,它会选择所有项。现在我在使用组件而不是钩子和函数之前遇到过这个问题。我尝试使用我在这里使用的相同方法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, index) => index.toString()}
                renderItem={({ item, index }) => (
                    <CheckBox 
                        center 
                        titleProps={{ color: 'black', 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', {
            method: 'POST',
            body: JSON.stringify({
                category: item,
                restaurantlocationcode: restaurantlocationcode,
            }),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        })
        .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;

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

【问题讨论】:

    标签: react-native react-hooks react-native-elements


    【解决方案1】:

    应用输出:

    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,
      },
    });
    

    工作示例:Expo Snack

    【讨论】:

    • 非常感谢您抽出时间来回答并帮助我解决这个问题。好的,所以我完全按照您在这里所拥有的,它摆脱了我收到的类型错误消息。但它根本没有选择任何东西。我认为这是复选框组件中的值行。当我输入 Value={item?.checked} 时,它在我的代码中出现错误。
    • 此外,当我单击任何按钮时,console.logged 都没有。似乎 onChange={} 没有做任何事情。
    • 我这边的逻辑和实现是完美的,您可以在提供的示例展览链接中看到它完美运行,有关更多详细信息,请提供您从中获取数据的上下文代码。问题出在我使用的数据形式或其他方面。
    • 哦,是的,不要误会我的意思,您的逻辑和实现与您发送的博览会链接一起工作。这就是为什么我如此困惑,因为我完全复制了你的方式,而我的根本没有点击任何项目。我会将我的上下文代码添加到原始问题中。
    • 不如把你的代码发布到expo上,这样我就可以更快地找到问题了。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多