react中获取选中行的数据

用selectedRows获取选中行的数据

在选中多选框时添加onChange方法存储selectedRows,在界面提交时直接获取selectedRows即可。

   //创建一个orderData对象,获取到选中行的所有数据后,赋值给orderData对象中的items属性
    let orderData = Object.assign({}, this.state.manualOrder, {
      items: this.state.selectedRows
    })

下面代码是整个jsx文件

import React, { Component } from 'react'
import { Table, Button, Row, Col, Divider, Select } from 'antd'
import PagenHeader from '../../components/PagenHeader'
import UploadPO from './UploadPO'
import classes from './ManualOrder.module.css'
import { getLocalStorage } from '../../utils/storage'
import { submitOrder } from '../../api/order'
import PageResult from '../../components/PageResult'
import BillShipForm from './BillShipForm'
import { getbillShip } from '../../api/bill_ship'

export default class ManualOrder extends Component {

  state = {
    manualOrder: {},
    poDataList: [],
    printType: null,
    isBillFormVisible: false,
    printTypeList: ['SB'],
    billShipInfo: {},
    showBillButton: false,
    selectedRowKeys: [],
    submiting: false,
    submitSuccessfully: false,
    uploadSuccessfully: false,
    disableSelected: false,
    pageResult: {
      statusCode: 0,
      message: null
    },
    successMsg: '',
    errorMsg: ''
  }

  parsePOData = (data) => {
    const poDataList = [];
    data.items.forEach(item => poDataList.push(item));
    this.setState({ manualOrder: data, poDataList: poDataList });
  };

  onUploadSuccessfully = (flag) => {
    this.setState({ uploadSuccessfully: flag })
  }

  handleSubmit = () => {
    this.setState({ submiting: true, disableSelected: true });

    const data = this.constructorManualOrder(this.state.manualOrder);
    submitOrder(data).then(res => {
      if (res.code === 4) {
        const resultMessage = 'Ordering completed. A notification mail have been send to you. If you cannot receive the notice mail within 2 hours,please contact our support team.'
        const pageResult = { statusCode: 0, message: resultMessage }
        this.parsePOData(res.data)
        this.setState({ submiting: false, disableSelected: false, submitSuccessfully: true, manualOrder: res.data, pageResult: pageResult });

      } else {
        const resultMessage = `Error submitting the order: ${res.message || res.msg}`
        const pageResult = { statusCode: 1, message: resultMessage }
        this.setState({ submiting: false, disableSelected: false, submitSuccessfully: false, pageResult: pageResult });
      }
    }, err => {
      const resultMessage = 'Error submitting the order:' + err + ". Please contact Avery Dennison Software Support Team software.support@ap.averydennison.com"
      const pageResult = { statusCode: 1, message: resultMessage }
      this.setState({ submiting: false, disableSelected: false, submitSuccessfully: false, pageResult: pageResult });
    })

  }
  handleDirectorCreateOrder = () => {
    window.location.href = '/kaloud/order/manualOrder'
  }
  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({selectedRowKeys:selectedRowKeys,selectedRows:selectedRows})
  };

  getBillShipInfo = () => {
    getbillShip().then(res => {
      if (res.code === 4) {
        const billData = res.data.billTo || {}
        const shipData = res.data.shipTo || {}
        const billShipInfo = {
          printLocation: null,
          billContact: billData.contact,
          billConpanyName: billData.companyName,
          billAddress1: billData.address1,
          billAddress2: billData.address2,
          billAddress3: billData.address3,
          billAddress4: billData.address4,
          billCity: billData.city,
          billState: billData.state,
          billZip: billData.zip,
          billCountry: billData.country,
          billPhone: billData.phone,
          billFax: billData.fax,
          shipContact: shipData.contact,
          shipCompanyName: shipData.companyName,
          shipAddress1: shipData.address1,
          shipAddress2: shipData.address2,
          shipAddress3: shipData.address3,
          shipAddress4: shipData.address4,
          shipCity: shipData.city,
          shipState: shipData.state,
          shipZip: shipData.zip,
          shipCountry: shipData.country,
          shipPhone: shipData.phone,
          shipFax: shipData.fax,
          shipVia: shipData.via
        }
        this.setState({ billShipInfo: billShipInfo })
      }
    }, err => {
      console.log(err)
    })
  }

  handlePrintTypeChange = (value) => {
    if (value === 'SB') {
      this.setState({ showBillButton: true })
    } else {
      this.setState({ showBillButton: false })
    }
    this.setState({ printType: value })
  }

  handleShowBillShip = () => {
    this.setState({ isBillFormVisible: true })
  }

  handleCloseForm = () => {
    this.setState({ isBillFormVisible: false })
  }

  onBillShipChange = (billShipFormData) => {
    this.setState({ billShipInfo: billShipFormData })
  }

  onUploadPORef = (ref) => {
    this.child = ref
  };

  constructorManualOrder = (manualOrder) => {
    //创建一个orderData对象,获取到选中行的所有数据后,赋值给orderData对象中的items属性
    let orderData = Object.assign({}, this.state.manualOrder, {
      items: this.state.selectedRows
    })

    const result = orderData;
    result.billShip = {
      billTo: this.state.billShipInfo.billTo,
      shipTo: this.state.billShipInfo.shipTo
    }
    result.printType = this.state.printType
    result.printLocation = this.state.billShipInfo.printLocation
    result.user = manualOrder.user === null ? getLocalStorage('user') : manualOrder.user
    this.setState({ manualOrder: result })
    return result;
  }
  goBack = () =>{
    this.setState({manualOrder: {},
      poDataList: [],
      isBillFormVisible: false,
      showBillButton: false,
      selectedRowKeys: [],
      submiting: false,
      submitSuccessfully: false,
      uploadSuccessfully: false,
      disableSelected: false,
      pageResult: {
        statusCode: 0,
        message: null
      },
      successMsg: '',
      errorMsg: ''})
  }
  renderColumns = () => {
    return [
      {
        title: 'Message',
        dataIndex: 'validateMsg',
        render: text => {
          if (text === 'Ready' || text === 'Success') {
            return <span>{text}</span>
          } else {
            return <span className="ant-typography ant-typography-danger" direction="ltr">{text}</span>
          }
        }
      },
      {
        title: 'Line No',
        dataIndex: 'rowNo'
      },
      {
        title: 'Factory Code',
        dataIndex: 'factoryCode'
      },
      {
        title: 'Quantity',
        dataIndex: 'orderQty'
      }
    ];
  }

  render() {
    //const user = getLocalStorage('user');
    const  result =new URLSearchParams(this.props.location.search)
    const user = result.get('user');
    const { manualOrder, poDataList, billShipInfo, isBillFormVisible, printTypeList ,disableSelected,selectedRowKeys
      ,uploadSuccessfully,showBillButton,submitSuccessfully,submiting, pageResult} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        disabled: record.validateMsg !== 'Ready' || disableSelected
      })
    };
    return (
        <div>
          <PagenHeader titleClass={classes.title}> Manual Order Form (User: {user})</PagenHeader>
          {
            (uploadSuccessfully === false) &&
            <UploadPO parsePOData={this.parsePOData} onUploadPORef={this.onUploadPORef} onUploadSuccessfully={this.onUploadSuccessfully} />
          }
          {
            (uploadSuccessfully === true) &&
            <div>
              <Row justify="center">
                <Col span={2} className={classes.label}>Select Print Type </Col>
                <Col span={3} className={classes.item}>
                  <Select
                      className={classes.item_width}
                      onChange={this.handlePrintTypeChange}
                      placeholder={' '}>
                    {printTypeList.map(printType => (
                        <Select.Option key={printType} >{printType}</Select.Option>
                    ))}
                  </Select>
                </Col>
                {showBillButton &&
                <Col span={2} >
                  <Button onClick={this.handleShowBillShip}>Bill Ship</Button>
                </Col>
                }
                <Col>
                  <BillShipForm isVisible={isBillFormVisible}
                                billShipInfo={billShipInfo}
                                closeForm={this.handleCloseForm} onBillShipChange={this.onBillShipChange} />
                </Col>
              </Row>
              <Divider orientation="left"></Divider>
              <Table
                  rowSelection={rowSelection}
                  pagination={false}
                  columns={this.renderColumns()}
                  dataSource={poDataList}
                  disabled={this.state.submitSuccessfully}
                  rowKey={record => record.rowNo}
              />
              <PageResult result={pageResult} titleClass={pageResult.statusCode === 0 ? classes.success_msg : classes.error_msg}>{pageResult.message}</PageResult>
              <Row justify="center" className={classes.submit}>
               { <Col span={2} >
                  <Button onClick={this.goBack} size="large" style={{ display: (submitSuccessfully ? 'none' : 'block') }}>Back</Button>
                </Col>}
                <Col offset={1} span={2} >
                  <Button type="primary" style={{ display: (submitSuccessfully ? 'none' : 'block') }}
                          size="large"
                          block
                          disabled={selectedRowKeys.length <= 0 || submiting}
                          onClick={this.handleSubmit}>
                    {submiting ? 'Submiting' : 'Submit'}
                  </Button>
                  <Button type="primary"
                          size="large"
                          block
                          onClick={this.handleDirectorCreateOrder} style={{ display: submitSuccessfully ? 'block' : 'none' }}>
                    New Order
                  </Button>
                </Col>
              </Row>
            </div>
          }
        </div>
    )
  }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MaterialReactTable 是一个 React UI 组件库,用于渲染数据表格。要获取选中数据,你可以使用 `onSelectionModelChange` 属性来监听选中的变化,然后在回调函数获取选中数据。 具体的代码示例如下: ``` import * as React from 'react'; import { DataGrid } from '@material-ui/data-grid'; const columns = [ { field: 'id', headerName: 'ID', width: 70 }, { field: 'firstName', headerName: 'First name', width: 130 }, { field: 'lastName', headerName: 'Last name', width: 130 }, { field: 'age', headerName: 'Age', type: 'number', width: 90 }, ]; const rows = [ { id: 1, lastName: 'Snow', firstName: 'Jon', age: 35 }, { id: 2, lastName: 'Lannister', firstName: 'Cersei', age: 42 }, { id: 3, lastName: 'Lannister', firstName: 'Jaime', age: 45 }, { id: 4, lastName: 'Stark', firstName: 'Arya', age: 16 }, { id: 5, lastName: 'Targaryen', firstName: 'Daenerys', age: null }, { id: 6, lastName: 'Melisandre', firstName: null, age: 150 }, { id: 7, lastName: 'Clifford', firstName: 'Ferrara', age: 44 }, { id: 8, lastName: 'Frances', firstName: 'Rossini', age: 36 }, { id: 9, lastName: 'Roxie', firstName: 'Harvey', age: 65 }, ]; export default function DataTable() { const [selectionModel, setSelectionModel] = React.useState([]); const handleSelectionModelChange = (newSelectionModel) => { setSelectionModel(newSelectionModel); console.log(newSelectionModel); // 输出选中的 id }; return ( <div style={{ height: 400, width: '100%' }}> <DataGrid rows={rows} columns={columns} checkboxSelection selectionModel={selectionModel} onSelectionModelChange={handleSelectionModelChange} /> </div> ); } ``` 在上面的示例,我们定义了一个 `DataGrid` 组件,设置 `checkboxSelection` 属性为 `true`,这样就可以在每一显示一个复选框。然后,在 `onSelectionModelChange` 回调函数,我们通过 `setSelectionModel` 更新选中数据,并通过 `console.log` 输出选中的 `id`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值