简体   繁体   English

如果选中将值添加到数组,则反应复选框

[英]React checkbox if checked add value to array

Hi this might be a very newbie question to ask but here is my question.嗨,这可能是一个非常新手的问题,但这是我的问题。 I have check boxes that represent all the days of the week.我有代表一周中所有日子的复选框。 If a day is checked I want to add it to a array so that on submit I can pass the array to back-end.如果选中了一天,我想将其添加到数组中,以便在提交时可以将数组传递到后端。 I copied check box structure from bootstrap to start with.我从引导程序复制复选框结构开始。 I tried to add logic to see if a box is checked and if it is checked I want to push it to my empty array in state.我尝试添加逻辑以查看是否选中了一个框,如果选中,我想将其推送到 state 中的空数组。 Also if a checkbox was checked but then unchecked I want to remove the item from the state array.此外,如果选中了复选框但未选中,我想从 state 数组中删除该项目。 So far I haven't found a way to make this all work.到目前为止,我还没有找到一种方法来完成这一切。

import React from 'react'

class CalenderSettingsModal extends React.Component {
    constructor(props) {
        super(props);
        this.state={
            workStart: 8,
            workEnd: '',
            workDays:[],

        }

        handleCheckboxChange = (event)=> this.setState({workDays: event.target.value});


    }

    render() {


        return (
            <React.Fragment>
                        <form>
                            <div>
                                <h5>Select your workday(s):</h5>
                                <div class="custom-control custom-checkbox " >
                                    <input type="checkbox" class="custom-control-input" id="monday" value="monday"  onChange={this.handleCheckboxChange}/>
                                    <label class="custom-control-label" for="monday">Monday</label>

                                </div>
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="tuesday" value="tuesday" onChange={ this.handleCheckboxChange}/>
                                    <label class="custom-control-label" for="tuesday">Tuesday</label>

                                </div>

                        </form>
                            <button >Save settings</button>



            </React.Fragment>

        );
    }
}

export default CalenderSettingsModal;

With this so far I tried to accomplish assigning the value to workDays when the box is checked but isn't working and I'm not sure how I could accomplish what I want to do.到目前为止,我试图在选中该框但不工作时完成将值分配给 workDays,我不确定如何完成我想做的事情。 Any insight would be appreciated.任何见解将不胜感激。

Right now, you are assigning the workDays array to a string type.现在,您正在将workDays数组分配给string类型。

You can use the spread operator to add values to your workDays state array.您可以使用spread运算符将值添加到workDays state 数组。 If event.target.id is already present in the workDays state you can filter it.如果event.target.id已经存在于workDays state 中,您可以对其进行过滤。 Here is the working code snippet.这是工作代码片段。

编辑 reverent-franklin-ziqrn

 handleCheckboxChange = event => {
    let newArray = [...this.state.workDays, event.target.id];
    if (this.state.workDays.includes(event.target.id)) {
      newArray = newArray.filter(day => day !== event.target.id);
    } 
    this.setState({
      workDays: newArray
    });
  };

See if this helps.看看这是否有帮助。

class CalenderSettingsModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      workStart: 8,
      workEnd: '',
      workDays: [],
    }
  }

  handleCheckboxChange = (event) => {
    if (event.target.checked) {
      if (!this.state.workDays.includes(event.target.value)) {
        this.setState(prevState => ({ workDays: [...prevState.workDays, event.target.value]}))
      }
    } else {
      this.setState(prevState => ({ workDays: prevState.workDays.filter(day => day !== event.target.value) }));
    }
  }


  render() {
    return (
      <React.Fragment>
        <form>
          <div>
            <h5>Select your workday(s):</h5>
            <div class="custom-control custom-checkbox" >
              {
                ["Monday", "Tuesday", /*... */].map(day => {
                  return (
                    <div class="custom-control custom-checkbox">
                      <input type="checkbox" class="custom-control-input" id={day} value={day} onChange={this.handleCheckboxChange} />
                      <label class="custom-control-label" for={day}>{day}</label>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </form>
        <button >Save settings</button>
      </React.Fragment>

    );
  }
}

It's not necessary to keep an array of what boxes are checked.没有必要保留选中哪些框的数组。 You can easily collect all the checked boxes when you save your data.保存数据时,您可以轻松收集所有选中的复选框。

const checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked');

If you have different groups of checkboxes, you can use a unique class to identify the group:如果您有不同的复选框组,您可以使用唯一的 class 来识别组:

const checkedBoxes = document.querySelectorAll('input[class=unique-class]:checked');
const [category_check_list, setCategoryCheckList] = useState([]);
const categoryCheckboxFilterHandler = e => {
    if (e.target.checked == true){
        setCategoryCheckList([...category_check_list, Number(e.target.value)]);
    }else{
        let check_list = [];
        category_check_list.map(check => {
            if (Number(check) != Number(e.target.value)){
                check_list.push(Number(check));
            }
        });
        setCategoryCheckList(check_list);
    }
};
var checked_category_id_list = category_check_list.toString();

then in the return i placed the following code and it worked perfect for me cause now its dynamic然后在返回中我放置了以下代码,它对我来说非常完美,因为它现在是动态的

return(
<>
 {categoriesQuery.isLoading ? (
   <span>Loading...</span>
    ) : categoriesQuery.isError ? (
    categoriesQuery.error.message
    ) : (
    categoriesQuery.data.slice(0, list_limit).map((category) => (
    <Grid item key={category.id} >
     <Paper className={paper}>
      <div className="form-check">
 <label htmlFor={category.id} className="form-check-label-form_check_label">
 <input className="form-check-label form_checkbox" type="checkbox" 
        name={category.category_name} value={category.id}  id={category.id} 
        onChange={e => categoryCheckboxFilterHandler(e)} />
             {category.category_name}
   </label>
                       </div>
               </Paper>
            </Grid>
         ))
             )}
   <>
)

i was using the material UI design hence the Grid and Paper, you can alternatively replace with div我使用的是材料 UI 设计,因此使用了 Grid 和 Paper,您也可以替换为 div

note: in order to run it properly you need to install react boostrap by the below command.注意:为了正确运行它,您需要通过以下命令安装 react boostrap。

npm i react-bootstrap npm 我反应引导

The question is answered but my code will help those who want to achieve it in react functional components, just copy paste the code and you will be able to know the logic behind it.问题已得到解答,但我的代码将帮助那些想要在反应功能组件中实现它的人,只需复制粘贴代码,您将能够了解其背后的逻辑。 I am using react bootstrap you can use anything, the concept is the same.我正在使用 react bootstrap 你可以使用任何东西,概念是一样的。

import React, {useState } from "react";
import Form from "react-bootstrap/Form";
import 'bootstrap/dist/css/bootstrap.min.css';

function RolesList(props) {


const [permissions,setPermissions] = useState([]);


const handleCheck = (event) => {
  var permissions_array = [...permissions];
  if (event.target.checked) {
    permissions_array = [...permissions, event.target.value];
  } else {
    permissions_array.splice(permissions.indexOf(event.target.value), 1);
  }
  setPermissions(permissions_array);

};


  return (
    <>
     
 <form> 
     <Form.Check 
        type={'checkbox'}
        name={"permission"}
        id={'permission'}
        label={'permission1'}
        value={'1'}
        onChange={handleCheck}

      />

<Form.Check 
        type={'checkbox'}
        name={"permission"}
        id={'permission'}
        label={'permission2'}
        value={'2'}
        onChange={handleCheck}

      />

</form>


    </>

)

}



export default RolesList

the code above will update the hooks likewise:上面的代码同样会更新钩子: 在此处输入图像描述

I've done it with functional component here's the code.Use the useEffect hook to console the latest value if you console directly in handleChange you will be 1 value behind from the latest value.我已经用功能组件完成了这里的代码。如果您直接在 handleChange 中进行控制台,请使用 useEffect 挂钩来控制台最新值,您将比最新值落后 1 个值。

Available for any help.可寻求任何帮助。

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

    export default function App() {
    const [dataArray, setdataArray] = useState([]);

    const handleChange = (e)=>{
    // setisChecked(e.target.checked);
    if(e.target.checked === true){
      setdataArray([...dataArray, e.target.value]);
    }
    else if(e.target.checked === false){
      let freshArray = dataArray.filter(val => val !== e.target.value);
      setdataArray([...freshArray]);
    }
  }

  useEffect(()=>{

    console.log(dataArray);

  }, [dataArray]);


  return (
    <>
    <input 
      type="checkbox"
      value='Monday'
      onChange={e => handleChange(e)} 
      />
      <span>Monday</span>

    <input 
      type="checkbox"
      value='Tuesday'
      onChange={e => handleChange(e)} 
      />
      <span>Tuesday</span>
    <input 
      type="checkbox"
      value='Wednesday'
      onChange={e => handleChange(e)} 
      />
      <span>Wednesday</span>
    <input 
      type="checkbox"
      value='Thursday'
      onChange={e => handleChange(e)} 
      />
      <span>Thursday</span>
    <input 
      type="checkbox"
      value='Friday'
      onChange={e => handleChange(e)} 
      />
      <span>Friday</span>
    <input 
      type="checkbox"
      value='Saturday'
      onChange={e => handleChange(e)} 
      />
      <span>Saturday</span>
    <input 
      type="checkbox"
      value='Sunday'
      onChange={e => handleChange(e)} 
      />
      <span>Sunday</span>
    </>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM