【问题标题】:Check one from the array of checkboxes从复选框数组中选中一个
【发布时间】:2020-11-23 08:40:02
【问题描述】:

我的任务是从 URL 加载过敏数组,并为每个过敏构建一个复选框。尽管以某种方式单击其中任何一个后,复选框都不会被选中,尽管底层过敏数组已更改并反映了“已选中”属性的更改。我一定忽略了一些微不足道的事情。

我的 React Native 组件:

import React, { useState, useContext, useEffect } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { Button, CheckBox } from 'react-native-elements';
import { OnboardingContext } from "../context/onboarding_context";

export function AllergyScreen({ navigation }) {
  const [isLoading, setLoading] = useState(true);
  const [allergies, setAllergies] = useState([]);
  const [state, setState] = useContext(OnboardingContext);

  useEffect(() => {
    fetch('https://foodstuff.com/api/allergies.json')
      .then((response) => response.json())
      .then((json) => setAllergies(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);

  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>CATEGORY: {state.category.name}</Text>
      <View style={{ flex: 1, padding: 24 }}>
          <FlatList
            data={allergies}
            keyExtractor={item => item.id.toString()}
            renderItem={({ item }) => (
              <CheckBox
                center
                title={item.name}
                checked={item.checked}
                onPress={() => {
                    item.checked = !item.checked;
                    Object.assign(allergies[allergies.findIndex(element => element.id === item.id)], item)
                    setAllergies(allergies);
                  }
                }
              />
            )}
          />
      </View>
    </View>
  );
}

过敏:

Array [
  Object {
    "checked": true,
    "created_at": "2020-11-14T10:35:18.883Z",
    "id": 1,
    "name": "Walnuts",
    "updated_at": "2020-11-14T10:35:18.883Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:25.345Z",
    "id": 2,
    "name": "Avocado",
    "updated_at": "2020-11-14T10:35:25.345Z",
  },
  Object {
    "checked": false,
    "created_at": "2020-11-14T10:35:31.829Z",
    "id": 3,
    "name": "Bad people",
    "updated_at": "2020-11-14T10:35:31.829Z",
  },
]

【问题讨论】:

    标签: reactjs react-native react-native-elements


    【解决方案1】:

    试试这个方法

    const onCheck = (index) => {
      const newData = [...allergies];
      newData[index].checked = !newData[index].checked;
      setAllergies(newData);
    
    }   
    
    renderItem={({ item, index }) => (
      <CheckBox
        ......
        onPress={() => { onCheck(index); }
        }
      />
    )}
    

    【讨论】:

      猜你喜欢
      • 2012-05-31
      • 2023-03-13
      • 2017-05-05
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多