How to implement the addition of react table: 1. Create two class components in a Table.jsx file; 2. Define variables outside the two components; 3. Create a click-added event method code as " handleAdd = () => { const { data, editingKey } = this.state;let newData = data;..." That's it.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to add a table in react?
React antd dynamically adds editable rows to Table
const EditableContext = React.createContext(); 2. First enter the code of the editable cell subcomponent
//子组件class EditableCell extends React.Component { getInput = () => { const { inputType } = this.props; let i = 1 if (inputType === 'rq') { //可根据不同的inputType来显示不同Form元素,inputType来源于父组件 return <datepicker></datepicker>; }else { return <input> } }; renderCell = ({ getFieldDecorator }) => { const { editing, dataIndex, title, record, children, ...restProps } = this.props; // console.log(record) return ( <td> {editing ? ( //editing使用父组件传过来的值,判断是否为编辑状态 <formitem> {getFieldDecorator(dataIndex, { rules: [{ required: dataIndex === 'bz' || dataIndex === 'id' ? false : true, message: `请输入!`, }, ], // initialValue: dataIndex && record[dataIndex] , initialValue: dataIndex && dataIndex === 'rq' ? (record[dataIndex] ? moment(record[dataIndex]) : null) : record[dataIndex] })(this.getInput())} </formitem> ) : ( children )} </td> ); }; render() { return <editablecontext.consumer>{this.renderCell}</editablecontext.consumer>; }}
class Schedule extends Component { state = { data: [], editingKey: '', dataSource: {}, }//Table渲染的columns,这里只写出三列举例子,在render方法内会重组该数组 columns = [ { className: "columnHead", title: '序号', dataIndex: 'id', key: 'id', width: 60, align: 'center', render: (text, row, index) => <span>{index + 1}</span> }, { className: "columnHead", title: '日期', dataIndex: 'rq', key: 'rq', align: 'center', width:100, editable: true,//editable: true是必须加的,哪一列需要编辑就加在哪列 }, { className: "columnHead", title: '从何地至何地', dataIndex: 'hdzhd', key: 'hdzhd', align: 'center', width:120, editable: true, }, { //该列为操作列,包含编辑、删除、取消、保存按钮,下面代码中的每个方法都在此处定义 className: "columnHead", title: '操作', align: 'center', render: (text, record) => { const { editingKey } = this.state; const editable = this.isEditing(record); return editable ? ( <span> <popconfirm> this.cancel(record.id)}> //添加了二次确实提醒 <a>取消</a> </popconfirm> <divider></divider> <editablecontext.consumer> //保存按钮要用EditableContext包起来 {(form) => ( <a> this.save(form, record.id, record)} style={{ marginRight: 8 }} >保存</a> )} </editablecontext.consumer> </span> ) : ( <span> <a> this.edit(record.id)}>编辑</a> <divider></divider> <popconfirm> this.delete(record.id)}> <a>删除</a> </popconfirm> </span> ); } } ] render(){ const components = { //在此处引入可编辑的单元格子组件 body: { cell: EditableCell, }, }; //重新处理了一下Table的columns const columns = this.columns.map((col) => { if (!col.editable) { return col; } return { ...col, //此处的数据会传给子组件 onCell: (record) => ({ record, inputType: col.dataIndex, dataIndex: col.dataIndex, title: col.title, editing: this.isEditing(record), }), }; }); return( <editablecontext.provider> <table> record.id} dataSource={data} columns={columns} scroll={{ x: "calc(620px + 10%)", y: WinHeight - 580 }} pagination={false} footer={() => <button>+ 新增</button>} /> ) }}The above code is the code that is simply displayed at the beginning of the page<p></p> <h5><a id="4_169">4. The default data is empty at first. Clicking the New button will add an editable row</a></h5>Figure 1<p><br><img src="https://img.php.cn/upload/image/514/968/618/1672885464479604.jpg" title="1672885464479604.jpg" alt="How to add react table"></p> <h5> <a id="5_172">5. Click on the new event method code</a><pre class="brush:php;toolbar:false">handleAdd = () => { //该方法在Table标签内的footer内定义 const { data, editingKey } = this.state; let newData = data; const id = new Date().toString(); if (newData.length === 0) { newData.push({ id, rq: '', hdzhd: '', gzdd: '', nfwdwfdw: '', gznr: '', bz: '' }) } else { if (editingKey !== '') { //如果上一条还处于编辑状态,不可新增 message.error('请先保存'); return; } const row = { id, rq: '', hdzhd: '', gzdd: '', nfwdwfdw: '', gznr: '', bz: '' }; newData.splice(data.length, 1, row); } this.setState({ data: newData, editingKey: id });};
Figure 2
Figure 3
save(form, key, record) { const { wsCgtzPjxx, data } = this.state; form.validateFields((error, row) => { if (error) { return; } const { data } = this.state; const newData = [...data]; row.rq = moment(row.rq).format('YYYY-MM-DD') //如果有日期选择框,要用format转一下 let dataobj = { //接口请求参数,只写了几个 rq: row.rq, hdzhd: row.hdzhd, gzdd: row.gzdd, } const index = newData.findIndex((item) => key === item.id); if (index > -1) { const item = newData[index]; newData.splice(index, 1, { ...item, ...row, }); http.post('单条数据保存接口调用').then(res => { if (res.code === 200) { this.initData();//保存后重新获取了一下表格数据 } }) this.setState({ data: newData, editingKey: '' }); } else { newData.push(row); http.post(调用接口, dataobj).then(res => { if (res.code === 200) { this.initData() } }) this.setState({ data: newData, editingKey: '' }); } });}
cancel = (key) => { if (this.state.isedit) { this.setState({ editingKey: '' }); } else { if (key.length > 6) { const { data } = this.state; const newData = data; newData.splice(data.length - 1, 1); this.setState({ data: newData, editingKey: key }); } this.setState({ editingKey: '' }); }};
Figure 4
At this time, the two operations in the operation column are "edit" and "delete"
edit = (key) => { this.setState({ editingKey: key, isedit: true });//让单元格变为编辑状态};
delete = (key) => { const { data } = this.state; const newData = data; const index = newData.findIndex((item) => key === item.id); http.get('调用删除接口', { id: key }).then(res => { this.initData() }) newData.splice(index, 1); this.setState({ data: newData, editingKey: '' });};
react video tutorial"
The above is the detailed content of How to add react table. For more information, please follow other related articles on the PHP Chinese website!