Yêu cầu thg 6 27, 2019 10:21 SA 4238 1 1
  • 4238 1 1
+3

ANT-DESIGN - Edit Cell trong Table

Chia sẻ
  • 4238 1 1

Ae cho mình hỏi, mình muốn edit cell trong table như ở ví dụ này: https://ant.design/components/table/#components-table-demo-edit-cell

Ví dụ ở trên, mình muốn edit dduocj trường First NameLast name

Mọi người hướng dẫn mình với, m loay hoay mãi mà chưa biết cách config Cảm ơn ae ạ !

1 CÂU TRẢ LỜI


Đã trả lời thg 6 27, 2019 11:45 SA
Đã được chấp nhận
+3

Bạn chú ý đến thuộc tính onCell của column nhé:

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });

onCell được dùng để pass thêm props vào table cell, cụ thể ở đây là custom component EditableCell để trong EditableCell có thể đọc được các prop editable, dataIndex, title...

=> Updated code đây nhé: https://codesandbox.io/s/exciting-hypatia-vvl8e

Mình move onCell lên phần khai báo columns luôn, bạn có thể sửa lại đoạn const columns = this.columns.map cho nó áp dụng cho cả children 😄

Diff:

-import { Table, Input, Button, Popconfirm, Form } from 'antd';
+import { Table, Input, Button, Form } from 'antd';
 
 const EditableContext = React.createContext();
 
@@ -20,12 +20,16 @@ class EditableCell extends React.Component {
     };
 
     toggleEdit = () => {
-        const editing = !this.state.editing;
-        this.setState({ editing }, () => {
-            if (editing) {
-                this.input.focus();
+        this.setState(
+            (prevState) => ({
+                editing: !prevState.editing,
+            }),
+            () => {
+                if (this.state.editing) {
+                    this.input.focus();
+                }
             }
-        });
+        );
     };
 
     save = (e) => {
@@ -78,19 +82,29 @@ class EditableTable extends React.Component {
         this.columns = [
             {
                 title: 'name',
                dataIndex: 'name',
                 children: [
                     {
                         title: 'First Name',
                         dataIndex: 'firstName',
                         width: 100,
-                        editable: true,
+                        onCell: (record) => ({
+                            record,
+                            editable: true,
+                            title: 'First Name',
+                            dataIndex: 'firstName',
+                            handleSave: this.handleSave,
+                        }),
                     },
                     {
                         title: 'Last Name',
                         dataIndex: 'lastName',
                         width: 100,
-                        editable: true,
+                        onCell: (record) => ({
+                            record,
+                            editable: true,
+                            title: 'Last Name',
+                            dataIndex: 'lastName',
+                            handleSave: this.handleSave,
+                        }),
                     },
                 ],
             },
@@ -149,27 +163,19 @@ class EditableTable extends React.Component {
                 cell: EditableCell,
             },
         };
-        const columns = this.columns.map((col) => {
-            if (!col.editable) {
-                return col;
-            }
-            return {
-                ...col,
-                onCell: (record) => ({
-                    record,
-                    editable: col.editable,
-                    dataIndex: col.dataIndex,
-                    title: col.title,
-                    handleSave: this.handleSave,
-                }),
-            };
-        });
+
         return (
             <div>
                 <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
                     Add a row
                 </Button>
-                <Table components={components} bordered dataSource={dataSource} columns={columns} />
+                <Table
+                    components={components}
+                    rowClassName={() => 'editable-row'}
+                    bordered
+                    dataSource={dataSource}
+                    columns={this.columns}
+                />
             </div>
         );
     }
Chia sẻ
Avatar Anh Tran @thanh_tuan
thg 6 29, 2019 11:25 CH

@pht Tuyệt vời. Cám ơn bạn nhiều nha

Avatar Anh Tran @thanh_tuan
thg 6 29, 2019 11:58 CH

@pht , bạn kiểm tra chô này giúp mình vs ạ.

https://codesandbox.io/s/stupefied-edison-y1nud

Thực tế các trường của mình là Start TimeEnd Time. Và mình phải valid theo điều kiện:

  • Định dạng: hh:mm:ss (1)
  • Start Time < End Time (2)

Điều kiện 1 mình đa thực hiện được, nhưng khi lấy giá trị start Time ra để kiểm tra điều kiện 2, mình log ra nó cứ bị undefined mà không biết tại sao. Mà có điều lạ là, nếu start time nhập đúng định dạng : hh:mm:ss thì ms bị còn khi bạn không nhập như định dạng kia thì se không bị undefine nưa

Đoạn này m chưa tìm được lý do vì sao. Bạn có thể giúp m được ko. Tks bạn rất nhiều

thg 6 30, 2019 4:51 SA

@thanh_tuan

Bạn chú ý đoạn này nhé:

    return editing ? (
      <Form.Item style={{ margin: 0 }}>
        {form.getFieldDecorator(dataIndex, {
          rules: rules,
          initialValue: record[dataIndex]
        })(
          <Input
            ref={node => (this.input = node)}
            onPressEnter={this.save}
            onBlur={this.save}
          />
        )}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingRight: 24 }}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );

Input có sự kiện onPressEnter, onBlur gọi đến hàm save

  save = e => {
      //
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      // 
    });
  };

Khi validate startTime thành công thì hàm save gọi đến toggleEdit tức là editing === false => lúc này react render thẻ div và không còn <Form.Item> nữa

=> Form không còn field startTime nữa.

Bạn thử sửa lại nhé 😄

Avatar Anh Tran @thanh_tuan
thg 6 30, 2019 8:01 SA

@pht ok bạn, m hiểu rồi. Để m sửa lại đoạn này. Cám ơn bạn nhiều nha 😄

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí