项目里有个需求是点击表格某行的工料机,显示对应定额下的工料机的表格数据,并能对两个表格进行增删改查,效果如下:
代码如下:
// 引入 Component 组件 import React, { Component } from ‘react‘; //定义子表显示 const EditableContext = React.createContext(); const EditableRow = ({ form, index, ...props }) => ( <EditableContext.Provider value={form}> <tr {...props} /> </EditableContext.Provider> ); const EditableFormRow = Form.create()(EditableRow); class EditableCell extends React.Component { getInput = () => { // 这里也可以通过其他值判断显示下拉框(比如dataIndex) if (this.props.inputType === ‘number‘) { return <InputNumber />; } return <Input />; }; render() { const { editing, dataIndex, title, inputType, record, index, ...restProps } = this.props; return ( <EditableContext.Consumer> {(form) => { const { getFieldDecorator } = form; return ( <td {...restProps}> {editing ? ( <FormItem style={{ margin: 0 }}> {getFieldDecorator(dataIndex, { rules: [{ required: true, message: `请填写${title}!`, }], initialValue: record[dataIndex], })(this.getInput())} </FormItem> ) : restProps.children} </td> ); }} </EditableContext.Consumer> ); } } // 将上面的配置应用到子表中 const components = { body: { row: EditableFormRow, cell: EditableCell, }, }; // 原始colums要把想要编辑的editable设置为true const columns = OriginalColumns.map((col) => { if (!col.editable) { return col; } return { ...col, onCell: record => ({ record, inputType: col.dataIndex === ‘age‘ ? ‘number‘ : ‘text‘, dataIndex: col.dataIndex, title: col.title, editing: this.isEditing(record), // 判断编辑哪一行 }), }; }); // 判断编辑哪一行的函数 isEditing = record => record.id === this.state.editingKey; <Table rowClassName="tableInput" dataSource={tableData} columns={columns} pagination={false} rowKey={record=>record.id} getTableData={this.getTableData} components={components} rowSelection={rowSelection} expandedRowRender={this.expandedRowRender} // 字列表扩展函数 expandIconColumnIndex={-1} // 隐藏默认展开样式 expandIconAsCell={false} // 隐藏默认展开样式 expandedRowKeys={expandedRowKeys} // 展开的行的id defaultExpandedRowKeys={expandedRowKeys} /> // 点击工料机,获取对应数据并展开,收起上一个展开的 expandTable=(record,index)=>{ this.setState({childTabData:[],parentTabId:record.id}) // 如果已经展开则收回,否则展开 let expandedRows = this.state.expandedRowKeys; if(expandedRows.includes(record.id)){ this.setState({expandedRowKeys: []}) }else{ // 获取数据并展开当前行 let arr = [] arr.push(record.id) this.getStuffListById(record.id) this.setState({expandedRowKeys:arr}) } }
原文:https://www.cnblogs.com/zpxm/p/10103997.html