【问题标题】:Flatlist with multiple checkbox React Native带有多个复选框的平面列表 React Native
【发布时间】:2022-02-10 21:04:21
【问题描述】:

我正在使用带有复选框的平面列表,我想将所选项目的数据保存到数组中,但无法将数据保存到数组中

我的 json 响应

{
 "tS_CT_CODE": "ELC",
 "tS_TASK_CODE": "ELC001",
 "tS_TITLE": "Light Problem",
 "tS_TITLE_AR": "",
 "tS_PRICE": 100.0,
 "tS_STATUS": "A",
 "tS_USER_ID": "",
 "tS_SYSTEM_DATE": ""
}

我想将 tsPrice 保存在不同的数组中,将 tsTitle 保存在不同的数组中,我只能在 taskName 中保存 ts_title,如下所示如何将 ts_price 保存在不同的数组中?

这是我的复选框

const [toggleCheckBox, setToggleCheckBox] = useState([]);

<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>

const handleListTap = async item => {
  const taskName = [...toggleCheckBox];
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
   } else {
     taskName.push(item.tS_TITLE);
   }
  console.log(taskName);
  setToggleCheckBox(taskName);
  // navigation.navigate('MaintenanceTimeSlot');
};

【问题讨论】:

  • “不同的数组”是什么意思?
  • like in taskName 只保存 ts_title 并创建其他数组,如 taskPrice 并保存 ts_Price

标签: arrays react-native checkbox react-native-flatlist react-functional-component


【解决方案1】:

从上面的代码中,我假设您将带有上述 JSON 响应对象的数组传递给 Flatlist 组件,而 CheckBox 是 Fl​​atlist 的子组件。因此,在这种情况下,您可以为价格创建另一个数组,如下所示

...
const [toggleCheckBox, setToggleCheckBox] = useState([]);
const [priceArray, setPriceArray] = useState([]);   // add this
...
<CheckBox
  checked={toggleCheckBox.includes(item.tS_TITLE)}
  onPress={() => handleListTap(item)}
/>
...
const handleListTap = async item => {
  let taskName = [...toggleCheckBox];
  let taskPrice = [...priceArray];    // add this
  const index = taskName.indexOf(item.tS_TITLE);
   if (index > -1) {
     taskName.splice(index, 1);
     taskPrice.splice(index, 1);     // add this
   } else {
     taskName.push(item.tS_TITLE);
     taskPrice.push(item.tS_TITLE);  // add this
   }
  console.log(taskName, taskPrice);
  setToggleCheckBox(taskName);
  setPriceArray(taskPrice);          // add this
  // navigation.navigate('MaintenanceTimeSlot');
};
...

【讨论】:

    猜你喜欢
    • 2022-11-21
    • 1970-01-01
    • 2018-04-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多