处理复选框

时间:2020-02-09 13:42:43

标签: reactjs react-hooks

我是新来的反应者,发现很难理解如何处理复选框。我正在打印的模块阵列非常多,但是我发现很难理解如何处理它们并动态检查它们 这是我的代码

import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { getSingleCompany, updateCompany } from '../../actions/companyAction';
import { getAllModules } from '../../actions/moduleAction';
import moment from 'moment';

const SingleCompanyInfo = ({ modules: { all_modules }, history, getAllModules, getSingleCompany, updateCompany, companies: { company_info }, loading: { loading }, match: { params: { company_id } }, error: { error } }) => {

  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    companyName: '',
    sub_domain: '',
    status: '',
    created_at: '',
    address: '',
    language_id: '',
    currency_id: '',
    deleted: '',
    companyModules: []
  });
  const [modules, setModules] = useState([]);

 
  const { first_name, last_name, email, companyName, sub_domain, created_at, status, address, language_id, currency_id, deleted, companyModules } = formData;

  useEffect(() => {

    if (firstShown) {
      getSingleCompany(company_id);
      getAllModules()
      setFirstShown(false);
    }

    if (error && error.message) {
      _errors.message = error.message;
      setErrors(_errors);
    };

    if (all_modules && all_modules.data && all_modules.data.modules) {
      setModules(all_modules.data.modules);
    }

  }, [getSingleCompany, all_modules, getAllModules, company_id, company_info, error, firstShown])

  const handleChange = e => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  }

 

 

  const handleCheckbox = event => {
    setCheckedItems({ ...checkedItems, [event.target.name]: event.target.checked });
    console.log("checkedItems: ", checkedItems);
  }

  return (
    <div>
      <form>
        <div className="card">
          <div className="card-header">
            <h3> Edit Company Info </h3>
          </div>
        </div>
        <div className="card-body">
          {formData && !isEmpty(formData) && !loading &&
            <>
              
              {
                modules && modules.map(item => (
                  <div className="custom-control custom-checkbox mr-2" key={item.id}>
                    <label className="custom-control-label" htmlFor={item.id} >
                      {item.name}

                      <input
                        type="checkbox"
                        className="custom-control-input form-control modules-checkbox"
                        defaultChecked={true}
                        id={item.id}
                        name={item.name}
                        onChange={handleCheckbox}
                      />
                    </label>
                  </div>
                ))
              }

              {_errors && _errors.message &&
                <div>
                  <input type="hidden" className="form-control is-invalid" />
                  <div className="invalid-feedback">
                    {_errors.message}
                  </div>
                </div>
              }
            </>
          }
          <div className="card-footer text-left">
            <button className="btn btn-blue" onClick={handleCompanyUpdate}>
              Update
          </button>
            <button className="ml-3  btn btn-blue" onClick={() => history.push('/admin/dashboard/companies')}>
              Back
          </button>
          </div>
          {loading &&
            <div style={{ left: '55%' }}>
              <Spinner />
            </div>
          }
        </div>
      </form>
    </div>

  )
}

const mapStateToProps = state => ({
  companies: state.companies,
  modules: state.modules,
  error: state.error,
  loading: state.loading
})

export default connect(mapStateToProps, { getAllModules, getSingleCompany, updateCompany })(withRouter(SingleCompanyInfo));

嘿,我是新来的反应者,目前正在处理表单,我想将一系列模块映射到复选框,但是我发现很难处理和检查这些复选框。

 if (all_modules && all_modules.data && all_modules.data.modules) {
      setModules(all_modules.data.modules);
    }




        {
                modules && modules.map(item => (
                  <div className="custom-control custom-checkbox mr-2" key={item.id}>
                    <label className="custom-control-label" htmlFor={item.id} >
                      {item.name}

                      <input
                        type="checkbox"
                        className="custom-control-input form-control modules-checkbox"
                        defaultChecked={true}
                        id={item.id}
                        name={item.name}
                        onChange={handleCheckbox}
                      />
                    </label>
                  </div>
                ))
              }

1 个答案:

答案 0 :(得分:0)

正如我在您的代码中看到的那样,您基本上想将选定的模块存储到某个数组中,例如,checkedItems。如果我对,那么您可以这样做

<input type="checkbox" className="custom-control-input form-control modules-checkbox"   id={item.id} name={item.name} 
checked={isSelected(item.id)}
onChange={()=>{handleCheckbox(item)}}
                  />

如您所见,我已使用isSelected方法检查天气项目是否已选中,并将项目对象传递给handleCheckbox方法 现在您的handleCheckbox方法应该像

handleCheckbox=(item)=>{
  // i assume you are using companyModulesto store selected module's id
  let companyModules=formData.companyModules;
  if(companyModules.includes(item.id)){
   // already checked ,make it unchecked
   companyModules.splice(companyModules.indexOf(item.id), 1)
  }else{
  //its not checked make if checked
    companyModules.push(item.id)
  }
//now update the formData
formData.companyModules=companyModules
setFormData(formData);
}

现在您的isSelected方法应如下所示

isSelected=(id)=>{
  return formData.companyModules.includes(id)
}

希望这会为您提供帮助,并使您清楚如何使用复选框

相关问题