react获取循环出来的复选框的值

  • 简单代码
import React, { Component } from "react";
import { Checkbox } from "semantic-ui-react";
import { getlistStaff } from "../action/registerAction";
import { connect } from "react-redux";
import "react-table/react-table.css";
import _ from "lodash";
class ReportSite extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allCheckDocValue: []
    };
  }
  handleDocCheck(data, i, staff) {
    const checkDoctorValue = {
      siteId: staff.siteId,
      index: i,
      checked: data.checked,
      email: staff.email
    };
    if (!_.isEmpty(checkDoctorValue) && checkDoctorValue.checked === true) {
      this.state.allCheckDocValue.push(checkDoctorValue);
    } else if (
      !_.isEmpty(checkDoctorValue) &&
      checkDoctorValue.checked === false
    ) {
      _.remove(this.state.allCheckDocValue, {
        siteId: checkDoctorValue.siteId,
        index: checkDoctorValue.index
      });
    }
    console.log("checkDoctorValue", checkDoctorValue);
  }
  componentDidMount() {
    const { getlistStaff } = this.props;
    getlistStaff();
  }
  render() {
    return (
      <div>
        {this.props.listStaff.map((staff, i) => {
          if (
            staff.siteId.indexOf(props.original.siteId) !== -1
          ) {
            const idName = "Doctor_Checkbox" + i;
            return (
              <div key={"staff-" + i}>
                <Checkbox
                  id={idName}
                  onChange={(e, data) =>
                    this.handleDocCheck(
                      data,
                      i,
                      staff
                    )
                  }
                  name="selectDoc"
                  label={
                    staff.isPrescribing
                      ? "Dr." + staff.lastName
                      : staff.firstName
                  }
                />
              </div>
            );
          }
          return null;
        })}
      </div>
    );
  }
}
const mapStateToProp = state => ({
  listStaff: state.patientsListStore.listStaff
});
const mapDispatchToProp = dispatch => ({
  getlistStaff: () => dispatch(getlistStaff())
});
export default connect(
  mapStateToProp,
  mapDispatchToProp
)(ReportSite);

然后选择之后,this.state.allCheckDocValue会将值一个个的打印出来,这时候,一般页面内还会有一个提交按钮,在提交按钮页面内将这些放在一个数组

for (let j = 0; j < this.props.allCheckDocValue.length; j++) {
      if (
        !_.isEmpty(this.props.allCheckDocValue[j]) &&
        this.props.allCheckDocValue[j].checked === true
      ) {
        selectValue = this.props.allCheckDocValue[j];
        this.state.allCheckDocValue.push(selectValue);
      } else if (
        !_.isEmpty(this.props.allCheckDocValue[j]) &&
        this.props.allCheckDocValue[j].checked === false
      ) {
        _.remove(this.state.allCheckDocValue[j], {
          siteId: this.props.allCheckDocValue[j].siteId,
          index: this.props.allCheckDocValue[j].index
        });
      }
    }
  • 实际项目中实现全选、取消全选(例子用到了redux)

效果图

App.js

import React, { Component } from "react";
import { Checkbox, Button } from "semantic-ui-react";
import "semantic-ui-css/semantic.min.css";
import SendReport from "./sendReport";
import { connect } from "react-redux";
import ReactTable from "react-table";
import "react-table/react-table.css";
import {
  changeDoctorSelect,
  changeReportList,
  resetAllReport
} from "../action/doctorReportAction";
class ReportSite extends Component {
  constructor(props) {
    super(props);
    this.handleClear = this.handleClear.bind(this);
  }
  handleClear() {
    const { resetAllReport } = this.props;
    resetAllReport();
  }
  handleSiteCheck(siteId) {
    const { changeReportList } = this.props;
    changeReportList(this, siteId);
  }
  handleDocCheck(siteId, staff) {
    const { changeDoctorSelect } = this.props;
    changeDoctorSelect(this, siteId, staff.email);
  }
  render() {
    return (
      <div className="boxlistcontainer">
        <ReactTable
          data={
            this.props.clinicSites &&
            this.props.clinicSites.map(p => {
              return {
                ...p
              };
            })
          }
          filterable
          defaultFilterMethod={(filter, row) =>
            String(row[filter.id]) === filter.value
          }
          columns={[
            {
              columns: [
                {
                  Header: "Actions",
                  accessor: "",
                  sortable: false,
                  filterable: false,
                  Cell: props => {
                    return (
                      <Checkbox
                        onChange={(e, data) =>
                          this.handleSiteCheck(props.original.siteId)
                        }
                        checked={this.props.reportList.hasOwnProperty(
                          props.original.siteId
                        )}
                        name="selectSite"
                      />
                    );
                  }
                }
              ]
            },
            {
              columns: [
                {
                  Header: "Doctor",
                  style: { overflow: "auto", textAlign: "left" },
                  accessor: "",
                  sortable: false,
                  filterable: false,
                  Cell: props => {
                    return (
                      <div>
                        {this.props.listStaff.map((staff, i) => {
                          if (
                            staff.siteId.indexOf(props.original.siteId) !== -1
                          ) {
                            const idName = "Doctor_Checkbox" + i;
                            return (
                              <div key={"staff-" + i}>
                                <Checkbox
                                  id={idName}
                                  checked={
                                    !!(
                                      this.props.reportList.hasOwnProperty(
                                        props.original.siteId
                                      ) &&
                                      this.props.reportList[
                                        props.original.siteId
                                      ].includes(staff.email)
                                    )
                                  }
                                  onChange={(e, data) =>
                                    this.handleDocCheck(
                                      props.original.siteId,
                                      staff
                                    )
                                  }
                                  name="selectDoc"
                                  label={
                                    staff.isPrescribing
                                      ? "Dr." + staff.lastName
                                      : staff.firstName
                                  }
                                />
                              </div>
                            );
                          }
                          return null;
                        })}
                      </div>
                    );
                  }
                }
              ]
            }
          ]}
          defaultPageSize={20}
          defaultSorted={[
            {
              id: "siteId",
              desc: false
            }
          ]}
          className="-striped -highlight"
          minRows={0}
        />
        <div className="add_import_box" style={{ textAlign: "center" }}>
          <SendReport />
          <Button size="small" onClick={this.handleClear}>
            Cancel
          </Button>
        </div>
      </div>
    );
  }
}
const mapStateToProp = state => ({
  clinicSites: state.patientsListStore.clinicSites,
  listStaff: state.patientsListStore.listStaff,
  reportList: state.reportListStore.reportList
});
const mapDispatchToProp = dispatch => ({
  省略几个获取listStaff,和clinicSites的接口,这个不属于本部分内容
  resetAllReport: () => dispatch(resetAllReport()),
  changeReportList: (self, siteId) => dispatch(changeReportList(self, siteId)),
  changeDoctorSelect: (self, siteId, doctorId) =>
    dispatch(changeDoctorSelect(self, siteId, doctorId))
});
export default connect(
  mapStateToProp,
  mapDispatchToProp
)(App);

sendReport.js

import React, { Component } from "react";
import { Modal, Button, Icon, Input } from "semantic-ui-react";
import { sendDocReport } from "../action/addAction";
import { connect } from "react-redux";
import ButtonSuccess from "./buttonSuccess";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import moment from "moment";
import _ from "lodash";
const ReportType = [{ type: "TEST", key: "1" }, { type: "DOCTOR", key: "2" }];
class sendReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      confirmSuccess: false,
      type: "TEST",
      toEmails: "",
      siteIds: [],
      doctorEmails: [],
      startDay: new Date(moment().add(-3, "days"))
    };
    this.handleConfirm.bind(this);
  }
  show = () => {
    this.setState({ open: true, confirmSuccess: false });
  };
  changeDay(date) {
    this.setState({ startDay: date });
  }
  handleTypeChange = event => {
    this.setState({ type: event.target.value });
  };
  changeEmail = event => {
    this.setState({ toEmails: event.target.value });
  };
  handleConfirm = () => {
    if (this.state.type === "TEST" && _.isEmpty(this.state.toEmails)) {
      alert("Please input email");
    } else if (this.state.type === "TEST" && !_.isEmpty(this.state.toEmails)) {
      this.setState({ confirmSuccess: true });
      const { sendDocReport } = this.props;
      const sendValue = {
        siteIds: this.state.siteIds,
        startDay: moment(this.state.startDay).format("YYYY-MM-DD"),
        type: this.state.type,
        toEmails: this.state.toEmails
      };
      sendDocReport(sendValue, this);
    } else if (this.state.type === "DOCTOR") {
      this.setState({ confirmSuccess: true });
      const { sendDocReport } = this.props;
      const sendValue = {
        siteIds: Object.keys(this.props.reportList),
        startDay: moment(this.state.startDay).format("YYYY-MM-DD"),
        type: "SEND_TO_DOCTOR",
        doctorEmails: JSON.stringify(this.props.reportList)
      };
      sendDocReport(sendValue, this);
    }
  };
  handleCancel = () =>
    this.setState({
      open: false,
      confirmSuccess: false,
      siteIds: [],
      doctorEmails: [],
      type: "TEST"
    });
  render() {
    const { open } = this.state;
    return (
      <Modal
        trigger={
          <Button size="small" onClick={this.show}>
            Send
          </Button>
        }
        open={open}
      >
        <Modal.Header>Send Report</Modal.Header>
        <Modal.Content>
          {this.state.confirmSuccess ? (
            <ButtonSuccess />
          ) : (
            <div className="newSite_box">
              <div className="inputTotal">
                <p className="inputLable">Start Day</p>
                <DatePicker
                  className="DOBPicker"
                  selected={this.state.startDay}
                  onChange={this.changeDay.bind(this)}
                />
              </div>
              <div className="inputTotal">
                <p className="inputLable">Type</p>
                <select
                  className="selectStyle"
                  onChange={(e, data) => {
                    this.handleTypeChange(e);
                  }}
                  ref={input => (this.type = input)}
                >
                  {ReportType.map((rtype, i) => {
                    return (
                      <option value={rtype.type} key={"rtype" + i}>
                        {rtype.type}
                      </option>
                    );
                  })}
                </select>
              </div>
              <div
                className="inputTotal"
                style={{
                  display: this.state.type === "TEST" ? "block" : "none"
                }}
              >
                <p className="inputLable">To Emails</p>
                <Input
                  placeholder="Johnsmith@email.com"
                  className="inputContent"
                  onChange={this.changeEmail}
                  value={this.state.toEmails}
                />
              </div>
            </div>
          )}
        </Modal.Content>
        <Modal.Actions style={{ textAlign: "center" }}>
          <Button
            color="green"
            onClick={e => this.handleConfirm()}
            style={{
              display: this.state.confirmSuccess ? "none" : "inline-block"
            }}
          >
            <Icon name="checkmark" />
            Ok
          </Button>
          <Button basic color="red" onClick={e => this.handleCancel()}>
            <Icon name="remove" />
            {this.state.confirmSuccess ? "Close" : "Cancel"}
          </Button>
        </Modal.Actions>
      </Modal>
    );
  }
}
const mapStateToProp = state => ({
  reportList: state.reportListStore.reportList
});
const mapDispatchToProp = dispatch => ({
  sendDocReport: (sendValue, self) => dispatch(sendDocReport(sendValue, self))
});
export default connect(
  mapStateToProp,
  mapDispatchToProp
)(sendReport);

doctorReportAction.js

import _ from "lodash";
import * as TYPES from "../types/types";

export function changeReportList(self, siteId) {
  return dispatch => {
    let docReportList = _.clone(self.props.reportList);
    if (docReportList.hasOwnProperty(siteId)) {
      delete docReportList[siteId];
    } else {
      let doctorList = [];
      _.forEach(self.props.listStaff, function(item) {
        if (item.siteId.includes(siteId)) {
          doctorList.push(item.email);
        }
      });
      Object.assign(docReportList, { [siteId]: doctorList });
    }
    dispatch(changeReportListStatus(docReportList));
  };
}

export function changeDoctorSelect(self, siteId, doctorId) {
  return dispatch => {
    let docReportList = _.clone(self.props.reportList);
    if (docReportList.hasOwnProperty(siteId)) {
      if (docReportList[siteId].includes(doctorId)) {
        let index = docReportList[siteId].indexOf(doctorId);
        docReportList[siteId].splice(index, 1);
        if (docReportList[siteId].length === 0) {
          delete docReportList[siteId];
        }
      } else {
        docReportList[siteId].push(doctorId);
      }
    } else {
      let doctorList = [];
      doctorList.push(doctorId);
      Object.assign(docReportList, { [siteId]: doctorList });
    }
    dispatch(changeReportListStatus(docReportList));
  };
}

function changeReportListStatus(reportList) {
  return {
    type: TYPES.DOCTOR_REPORT_LIST,
    text: reportList
  };
}

export function resetAllReport() {
  return dispatch => {
    dispatch(resetAllReportState());
  };
}
function resetAllReportState() {
  return {
    type: TYPES.RESET_ALL_REPORT
  };
}

types.js

export const DOCTOR_REPORT_LIST = "doctor_report_list";
export const RESET_ALL_REPORT = "reset_all_report";

reducer.js

import * as TYPES from "../types/types";

const initialState = {
  reportList: {}
};

export default function reportListReducer(state = initialState, action) {
  switch (action.type) {
    case TYPES.DOCTOR_REPORT_LIST:
      return {
        ...state,
        reportList: action.text
      };
    case TYPES.RESET_ALL_REPORT:
      return {
        ...state,
        reportList: {}
      };
    default:
      return state;
  }
}

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值