如何在多复选框中设置选中项为真或假本机反应

时间:2021-04-02 13:10:33

标签: reactjs react-native

我有个小小的要求

我想知道如何通过子条款反应原生在多复选框中设置选中的项目真或假

在下面的代码中,当我点击复选框时,我想在函数 onchecked() 中更改数组中的相关项并更新组件。

import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  Text,
  View,
  CheckBox,
  TouchableOpacity,
} from "react-native";

const terms = [
  {
    term_id: 21,
    name: "Clothing",
    checked: false,
    children: [
      {
        term_id: 24,
        name: "Accessories",
        checked: false,
        children: [
          {
            term_id: 25,
            name: "Scarf",
            checked: false,
            children: [],
          },
          {
            term_id: 22,
            name: "Tshirts",
            checked: false,
            children: [],
          },
        ],
      },
    ],
  },
];

export default function Categoris() {
  const [unSelectedterms, setSelectionTerms] = useState(terms);

  const onchecked = (id) => {
    console.log(id);

    setSelectionTerms(unSelectedterms);
  };

  const recursive = (data, level = 0) => {
    return data.map((item, key) =>
      item.children?.length ? (
        <>
          {renderItem(level, item.name, item.term_id, item.checked, key)}
          {recursive(item.children, level + 1)}
        </>
      ) : (
        renderItem(level, item.name, item.term_id, item.checked, key)
      )
    );
  };

  const renderItem = (level, name, id, checked, key) => (
    <TouchableOpacity
      style={{ flexDirection: "row", alignItems: "center" }}
      key={key}
      onPress={() => {
        onchecked(id);
      }}
    >
      <CheckBox
        value={checked}
        onValueChange={() => {
          onchecked(id);
        }}
      />

      <Text style={{ fontWeight: "bold" }}>
        {name}
        {id} {level > 0 && "- ".repeat(level)}
      </Text>
    </TouchableOpacity>
  );

  return <View style={styles.container}>{recursive(unSelectedterms)}</View>;
}

const styles = StyleSheet.create({
  item: {
    fontSize: 20,
  },
  container: {
    backgroundColor: "#fff",
    padding: 50,
  },
});

在下面的代码中,当我点击复选框时,我想在函数 onchecked() 中更改数组中的相关项并更新组件。

1 个答案:

答案 0 :(得分:0)

一种选择是编写一些代码来遍历 terms 树并更新正确的 checked 值,但我可能会建议另一种方法。而是将 checked 状态与 terms 树分开存储以简化状态更新。

const [checkedStates, setCheckedStates] = useState({});
const onChecked(id) => {
  // this will toggle based on the current value of the checkbox
  setCheckedStates(current => ({
    ...current,
    [id]: !current[id],
  });
}
...

// and then in the recursive call
{renderItem(level, item.name, item.term_id, !!checkedStates[item.id], key)}

这种方法应该避免更复杂的树遍历和以额外的状态为代价的更新。如果不需要更新 terms 中的其他属性,我会选择权衡,但如果可以更新 terms 的其他部分,那么树遍历可能是更好的选择。