Reactjs 从所选复选框设置数组

Reactjs 从所选复选框设置数组,reactjs,Reactjs,我对react有点陌生,所以我希望在这里得到正确方向的推动。我要做的是,一旦更改复选框,我需要查询选中了哪些复选框,并使用选定的值创建一个数组。下面是当前代码 import React, {useState, useEffect} from 'react' import axios from 'axios'; function Formats(props) { const FormatsApi = 'props.serverUrl' // Get data from api c

我对react有点陌生,所以我希望在这里得到正确方向的推动。我要做的是,一旦更改复选框,我需要查询选中了哪些复选框,并使用选定的值创建一个数组。下面是当前代码

import React, {useState, useEffect} from 'react'
import axios from 'axios';


function Formats(props) {
  const FormatsApi = 'props.serverUrl'

  // Get data from api
  const [formats, setFormats ] = useState([])

  // Need to query checkboxes and set array with values
  function handleChange(e) {
      // set array here
  }
  
  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(FormatsApi)
      console.log(result.data)
      setFormats(result.data)
    }
    fetchData();
  }, []);

  return (
    <div className="row">
      {formats.map(format => (
        <div className="col-1 d-flex align-items-center justify-content-end" key={format.key_string}>
          <label className="mr-2 mb-0">{format.key_string}</label>
          <input type="checkbox" name={format.key_string} value={format.id} onChange={handleChange}/>
        </div>
      ))}
      
    </div>
  )
}

export default Formats
import React,{useState,useffect}来自“React”
从“axios”导入axios;
功能格式(道具){
const FormatsApi='props.serverUrl'
//从api获取数据
const[formats,setFormats]=useState([])
//需要查询复选框并使用值设置数组
功能手柄更改(e){
//在这里设置数组
}
useffect(()=>{
const fetchData=async()=>{
常量结果=等待axios(FormatsApi)
console.log(result.data)
setFormats(result.data)
}
fetchData();
}, []);
返回(
{formats.map(格式=>(
{format.key_string}
))}
)
}
导出默认格式

你必须在某处保持一系列的可见性。。。您可以在每次单击每个复选框时对其进行更新

相关JS

import React, { useState, useEffect } from "react";
// import axios from "axios";

const mockData = {
  data: [
    { key_string: "1", id: 1 },
    { key_string: "2", id: 2 },
    { key_string: "3", id: 3 },
    { key_string: "4", id: 4 }
  ]
};

function Formats(props) {
  const FormatsApi = "props.serverUrl";

  // Get data from api
  const [formats, setFormats] = useState([]);
  const [formatsCheckBoxRecord, setFormatsCheckBoxRecord] = useState([]);

  // Need to query checkboxes and set array with values
  function handleChange(e) {
    // set array here
    let beforeUpdateArray = [...formatsCheckBoxRecord];
    let relevantEntry = beforeUpdateArray.find(
      x => x.id.toString() === e.target.value.toString()
    );
    let relevantEntryIndex = beforeUpdateArray.findIndex(
      x => x.id.toString() === e.target.value.toString()
    );
    relevantEntry.checkStatus = !relevantEntry.checkStatus;
    beforeUpdateArray[relevantEntryIndex] = relevantEntry;
    setFormatsCheckBoxRecord(beforeUpdateArray);
  }

  useEffect(() => {
    const fetchData = async () => {
      setTimeout(() => {
        const result = mockData; // await axios(FormatsApi);
        console.log(result.data);
        setFormats(result.data);
        let formatsCheckBoxRecordArray = [];
        for (var i = 0; i < result.data.length; i++) {
          formatsCheckBoxRecordArray.push({
            id: result.data[i].id,
            checkStatus: false
          });
        }
        setFormatsCheckBoxRecord(formatsCheckBoxRecordArray);
        // console.log(formatsCheckBoxRecordArray);
      }, 20);
    };
    fetchData();
  }, []);

  return (
    <div className="contianer">
      <div className="row">
        {formats && formats.length > 0
          ? formats.map(format => (
              <div
                className="col-1 d-flex align-items-center justify-content-end"
                key={format.key_string}
              >
                <label className="mr-2 mb-0">{format.key_string}</label>
                <input
                  type="checkbox"
                  name={format.key_string}
                  value={format.id}
                  onChange={handleChange}
                />
              </div>
            ))
          : null}
      </div>
      <div className="row">
        {formatsCheckBoxRecord && formatsCheckBoxRecord.length > 0
          ? formatsCheckBoxRecord.map(val => (
              <div>
                {val.id} [{val.checkStatus.toString()}]
              </div>
            ))
          : null}
      </div>
    </div>
  );
}

export default Formats;
import React,{useState,useffect}来自“React”;
//从“axios”导入axios;
常数mockData={
数据:[
{key_string:“1”,id:1},
{key_string:“2”,id:2},
{key_string:“3”,id:3},
{key_字符串:“4”,id:4}
]
};
功能格式(道具){
const FormatsApi=“props.serverUrl”;
//从api获取数据
const[formats,setFormats]=useState([]);
常量[formatsCheckBoxRecord,setFormatsCheckBoxRecord]=useState([]);
//需要查询复选框并使用值设置数组
功能手柄更改(e){
//在这里设置数组
let beforeUpdateArray=[…formatsCheckBoxRecord];
让relevantEntry=beforeUpdateArray.find(
x=>x.id.toString()==e.target.value.toString()
);
让RelevantryIndex=beforeUpdateArray.findIndex(
x=>x.id.toString()==e.target.value.toString()
);
relevantry.checkStatus=!relevantry.checkStatus;
beforeUpdateArray[RelevantientryIndex]=相关条目;
setFormatsCheckBoxRecord(在UpdateArray之前);
}
useffect(()=>{
const fetchData=async()=>{
设置超时(()=>{
const result=mockData;//等待axios(FormatsApi);
console.log(result.data);
setFormats(result.data);
让formatsCheckBoxRecordArray=[];
对于(var i=0;i0
?formats.map(格式=>(
{format.key_string}
))
:null}
{formatsCheckBoxRecord&&formatsCheckBoxRecord.length>0
?formatsCheckBoxRecord.map(val=>(
{val.id}[{val.checkStatus.toString()}]
))
:null}
);
}
导出默认格式;

工作

下面这样简单的方法可以将选中的复选框存储在状态中

// create a state variable to store the checkbox selection
const [checkSelection, setCheckSelection] = useState([]);

function handleChange(e) {
    if (e.currentTarget.checked) {
        setCheckSelection([...checkSelection, e.target.value]);
    } else {
        const newArr = checkSelection.filter((item) => item !== e.target.value);
        setCheckSelection(newArr);
    }
}

在这里工作。

这看起来是一个很好的解决方案。这个答案是否能满足您的需求?