EditableProTable 可编辑表格
在 ProTable 的列定义上增加行内编辑、新增、校验、异步保存、删除和拖拽排序能力,并把成功结果写回应用拥有的 []T。
何时使用
- 列表中的少量字段需要直接编辑、保存或取消,而不想打开独立表单时。
- 新增行需要先经过必填、规则或异步查重,再加入受控数据时。
- 需要同时展示格式化只读列和少量可编辑列时。
- 复杂跨步骤编辑、字段很多或需要强制聚焦时,用 ProForm 高级表单 或 ModalForm 弹窗表单 更合适。
在线体验
基本用法
下面代码放在应用的页面文件中;完整的 main 和窗口初始化见打开自绘窗口。每个可编辑列必须同时提供 Editor 和 Set,否则该列只读。
package main
import "github.com/tangoui/tango/ui"
type person struct {
ID string
Name string
Age float64
}
var people = []person{{ID: "p1", Name: "Alice", Age: 30}}
var personColumns = []ui.ProColumn[person]{
{Key: "name", Title: "姓名", Value: func(r person) any { return r.Name },
Editor: &ui.ProField{Required: true},
Set: func(r *person, v any) { r.Name, _ = v.(string) }},
{Key: "age", Title: "年龄", ValueType: ui.ValueDigit,
Value: func(r person) any { return r.Age },
Editor: &ui.ProField{Min: 0, Max: 150},
Set: func(r *person, v any) { r.Age, _ = v.(float64) }},
{Key: "op", Title: "操作", ValueType: ui.ValueOption},
}
func page(c *ui.Context) {
ui.EditableProTable(c, personColumns, &people).
Title("人员").
RowKey(func(r person) string { return r.ID }).
Show()
}
func main() {}点击行操作中的编辑后,Editor 根据列的 ValueType 生成控件;保存前运行字段规则,成功后通过 Set 把草稿写回 *rows。默认一次只编辑一行。
常见用法
新增行与异步保存
NewRow 显示“添加一行数据”,新行先处于编辑状态,保存通过校验后才加入 *rows。OnSave 收到的 index 对已有行是原索引,对新行是 -1。
package main
import "github.com/tangoui/tango/ui"
type item struct{ ID, Title string }
var (
items = []item{{ID: "i1", Title: "第一项"}}
nextID = 1
itemColumns = []ui.ProColumn[item]{
{Key: "title", Title: "标题", Value: func(r item) any { return r.Title },
Editor: &ui.ProField{Required: true},
Set: func(r *item, v any) { r.Title, _ = v.(string) }},
}
)
func page(c *ui.Context) {
ui.EditableProTable(c, itemColumns, &items).
RowKey(func(r item) string { return r.ID }).
NewRow(func() item {
nextID++
return item{ID: "new" + string(rune('0'+nextID))}
}).
OnSave(func(row item, index int, done func(error)) {
go done(saveItem(row, index))
}).
Show()
}
func saveItem(row item, index int) error { return nil }
func main() {}调用 done(err) 并传入非空错误时,行保持编辑状态并显示错误。调用 done(nil) 后才写回数据。实际项目中应使用稳定且唯一的 RowKey。
受控编辑、多行编辑和限制行
EditableKeys 绑定正在编辑的行 key,页面可以预先打开某行或在外部控制编辑集合。默认只允许一行,Multiple() 允许多行;RowEditable 可以按业务状态限制编辑。
package main
import "github.com/tangoui/tango/ui"
type task struct{ ID, Name, State string }
var (
tasks = []task{{ID: "t1", Name: "设计", State: "open"}, {ID: "t2", Name: "发布", State: "done"}}
editing = []string{"t1"}
taskColumns = []ui.ProColumn[task]{
{Key: "name", Title: "任务", Value: func(r task) any { return r.Name },
Editor: &ui.ProField{Required: true}, Set: func(r *task, v any) { r.Name, _ = v.(string) }},
{Key: "state", Title: "状态", ValueType: ui.ValueSelect,
ValueEnum: []ui.ProEnum{{Value: "open", Label: "进行中"}, {Value: "done", Label: "完成"}},
Value: func(r task) any { return r.State },
Editor: &ui.ProField{}, Set: func(r *task, v any) { r.State, _ = v.(string) }},
}
)
func page(c *ui.Context) {
ui.EditableProTable(c, taskColumns, &tasks).
RowKey(func(r task) string { return r.ID }).
EditableKeys(&editing).
Multiple().
RowEditable(func(r task) bool { return r.State != "done" }).
Show()
}
func main() {}受控 key 必须与 RowKey 返回值一致,删除数据时应同步移除已删除行的编辑键。直接读取 editing 获取编辑集合。Changed() 报告的是保存、删除或重排。
字段规则与异步校验
Editor 可以配置 Required、Rules、Validate 和 AsyncValidate。同步规则先执行,全部通过后才运行异步校验;校验期间 Validating(key) 为 true。
package main
import "github.com/tangoui/tango/ui"
type account struct{ ID, Name string }
var accounts = []account{{ID: "a1", Name: "TanGo"}}
var accountColumns = []ui.ProColumn[account]{
{Key: "name", Title: "名称", Value: func(r account) any { return r.Name },
Editor: &ui.ProField{
Required: true,
Rules: []ui.Rule{ui.MaxLen(20, "最多 20 个字符")},
AsyncValidate: func(v any, done func(string)) {
go func() {
if v == "已占用" {
done("名称已存在")
return
}
done("")
}()
},
},
Set: func(r *account, v any) { r.Name, _ = v.(string) }},
}
func page(c *ui.Context) {
table := ui.EditableProTable(c, accountColumns, &accounts).
RowKey(func(r account) string { return r.ID }).
Show()
if table.Validating("a1") {
ui.Text(c, "正在检查名称……").Tertiary()
}
}
func main() {}Errors(key) 返回该行按列 key 保存的错误消息;异步回调可以从 goroutine 调用 done,组件会在 UI 失效后重新检查结果。
新增、分页和拖拽排序
Pagination(n) 在本地按每页 n 行显示,AddAtTop() 让草稿行和添加按钮位于表格上方,DragSort 在 *rows 重排后回调原始索引。
package main
import "github.com/tangoui/tango/ui"
type row struct{ ID, Label string }
var rows = []row{{ID: "1", Label: "一"}, {ID: "2", Label: "二"}, {ID: "3", Label: "三"}}
var columns = []ui.ProColumn[row]{
{Key: "label", Title: "名称", Value: func(r row) any { return r.Label },
Editor: &ui.ProField{Required: true}, Set: func(r *row, v any) { r.Label, _ = v.(string) }},
}
func page(c *ui.Context) {
ui.EditableProTable(c, columns, &rows).
RowKey(func(r row) string { return r.ID }).
NewRow(func() row { return row{ID: "new"} }).
AddAtTop().
Pagination(10).
DragSort(func(from, to int) { recordMove(from, to) }).
Bordered().
Show()
}
func recordMove(from, to int) {}
func main() {}新行在保存前不会参与已保存数据的拖拽排序;如果需要服务端排序,把移动回调交给保存接口,并在回调中同步应用状态。
自定义删除、保存错误和工具栏
OnDelete(func(row T, index int)) 在确认删除后调用,由回调负责更新 *rows。未设置回调时,组件直接删除对应行。ToolBar 可以放批量操作或状态信息,NoDelete() 隐藏删除动作。
package main
import "github.com/tangoui/tango/ui"
type record struct{ ID, Name string }
var records = []record{{ID: "r1", Name: "记录"}}
var recordColumns = []ui.ProColumn[record]{
{Key: "name", Title: "名称", Value: func(r record) any { return r.Name },
Editor: &ui.ProField{}, Set: func(r *record, v any) { r.Name, _ = v.(string) }},
}
func page(c *ui.Context) {
table := ui.EditableProTable(c, recordColumns, &records).
Title("记录").
ToolBar(func() { ui.Button(c, "导出").Small() }).
RowKey(func(r record) string { return r.ID }).
OnDelete(func(row record, index int) { archive(row) }).
NoDelete().
Show()
if table.Saved() || table.Deleted() {
refreshSummary()
}
}
func archive(row record) {}
func refreshSummary() {}
func main() {}上述示例用 NoDelete() 隐藏删除动作。移除它即可启用删除。远程保存通过 OnSave 的 done 报告结果。
大量数据:虚拟滚动
ScrollY(px) 限制表体高度并启用窗口化构建。Virtual() 显式声明虚拟模式,在 Element Plus 主题下采用 Table V2 的 50px 行高,其余情况跟随 Size。CellEditorTable 和 RowEditorTable 有同样的两个方法。
当前页正在编辑的行(或格所在的行)滚出视口后仍会构建,保留草稿和焦点。开始编辑(Edit、AddRow)、焦点移进正在编辑的行(例如 Tab 到它的下一个编辑器)、在滚出视口的编辑器里输入,以及校验失败时,表格会把这一行滚进视口。表头、工具栏和添加按钮留在滚动区外。ScrollY 默认为 0,此时构建当前页的全部行。
有 ScrollY 时,表格会记住未在当前页找到的编辑键。原地改写行的 key 且行数不变时,重新出现的编辑键要等到行数变化或传入使用新底层存储的 rows 切片才会再次查找。
func bigTable(c *ui.Context, cols []ui.ProColumn[row], rows *[]row) {
ui.EditableProTable(c, cols, rows).RowKey(func(r row) string { return r.ID }).
ScrollY(480).Virtual().Show()
}主题与样式
EditableProTable 的单元格、编辑控件和操作链接复用 ProTable、Table、ProField 的主题令牌。可通过 ConfigProvider.Defaults("EditableProTable", ui.Props{...}) 设置 size、bordered、pagination、maxLength 默认值;Bordered、Size、Pagination 等实例方法优先。三套主题会调整表格边框、编辑态控件和操作按钮,不改变 Set 或校验流程。
注意事项
rows是应用拥有的切片,只有校验和OnSave成功后才会写回;不要在OnSave之前直接修改原行来模拟草稿。RowKey在新增、删除和拖拽排序时必须稳定且唯一;默认索引只适合不会重排的静态数据。OnSave和异步校验完成后都要调用done。Validating(key)在异步校验或保存未完成时为true。- 大数据量可用
Pagination、上层的服务端分页或ScrollY(px).Virtual()。窗口化时,当前页构建可见行和保留的编辑行。无障碍树仅包含已构建的行,表格仍会报告完整行数。 - 操作列和编辑控件已有键盘语义;自定义
Render或ToolBar中的图标按钮要设置A11yLabel。
示例代码
以下是上方在线演示运行的 Go 源码(来自官方 gallery),点击标题展开。函数接收的 c *ui.Context 由窗口的 UI 循环每帧传入,接入方式见 Go GUI 入门。
EditableProTable 可编辑表格
gallery 演示 EditableProTable 的注册调用(含 Render 函数),源码 page_p2e_table.go#L49。
加载中…
API
签名与说明由 site/tools/compdoc 从 Go 源码和文档注释提取;点击名称跳到 Go API 参考 的对应条目。
入口函数
ui.EditableProTable
func EditableProTable[T any](c *Context, cols []ProColumn[T], rows *[]T) *EditableProTableW[T]EditableProTable starts an editable table over *rows; chain options, then Show.
返回 *EditableProTableW,可链式调用的方法见 EditableProTableW 方法。
ui.CellEditorTable
func CellEditorTable[T any](c *Context, cols []ProColumn[T], rows *[]T) *CellEditorTableW[T]CellEditorTable starts a cell-editing table over *rows; chain options, then Show.
ConfigProvider.Defaults("CellEditorTable", ...) keys: "bordered" (bool, default true), "size", "pagination" (page size or Props{"pageSize": n}; default none).
返回 *CellEditorTableW,可链式调用的方法见 CellEditorTableW 方法。
ui.RowEditorTable
func RowEditorTable[T any](c *Context, cols []ProColumn[T], rows *[]T) *RowEditorTableW[T]RowEditorTable starts a row-editing table over *rows; chain options, then Show.
ConfigProvider.Defaults("RowEditorTable", ...) keys: "bordered" (bool, default true), "size", "pagination" (page size or Props{"pageSize": n}; default none).
返回 *RowEditorTableW,可链式调用的方法见 RowEditorTableW 方法。
EditableProTableW 方法
ui.EditableProTableW:EditableProTableW is a table over app-owned rows edited in place (Ant Design Pro EditableProTable): columns with an Editor show the ProField control of their value type while a row is edited; an action column offers edit / save / cancel / delete; "add a row" creates a draft row that joins the data when saved. Rows are validated (Required, Rules, Validate, AsyncValidate of every editor) before they are written back.
ui.EditableProTable(c, cols, &rows).RowKey(func(r Row) string { return r.ID }).
NewRow(func() Row { return Row{ID: newID()} }).
OnSave(func(r Row, i int, done func(error)) { go save(r, done) }).
Show()
| 方法 | 说明 | 签名 |
|---|---|---|
AddAtTop | AddAtTop puts new rows (and the add button) above the data. | AddAtTop() *EditableProTableW[T] |
AddRow | AddRow adds a new draft row in edit mode (as the add button does) and returns its key ("" when NewRow is not set or another row is being edited in single mode). | AddRow() string |
Bordered | Bordered draws cell borders. | Bordered() *EditableProTableW[T] |
Cancel | Cancel leaves edit mode of row k without saving (a new row is dropped). | Cancel(k string) |
Changed | Changed reports any change of *rows in the last Show. | Changed() bool |
Deleted | Deleted reports a deleted row in the last Show. | Deleted() bool |
DragSort | DragSort adds a drag handle column that reorders *rows; fn (may be nil) is told the move (indices into *rows) after it happened. | DragSort(fn func(from, to int)) *EditableProTableW[T] |
Edit | Edit puts the row with key k into edit mode (valid after Show). | Edit(k string) |
EditableKeys | EditableKeys binds the keys of the rows being edited (controlled). | EditableKeys(keys *[]string) *EditableProTableW[T] |
Editing | Editing reports whether the row with key k is in edit mode. | Editing(k string) bool |
Errors | Errors returns the validation messages of the row with key k by column key (nil when valid). | Errors(k string) map[string]string |
ID | ID returns the widget ID (valid after Show). | ID() ID |
MaxLength | MaxLength hides the add button once there are n rows. | MaxLength(n int) *EditableProTableW[T] |
Moved | Moved reports a drag-sort move in the last Show. | Moved() bool |
Multiple | Multiple lets several rows be edited at once (default: one; the other rows' edit actions are disabled meanwhile). | Multiple() *EditableProTableW[T] |
NewRow | NewRow shows the "add a row" button; fn creates the draft row (set its key there). | NewRow(fn func() T) *EditableProTableW[T] |
NoDelete | NoDelete hides the delete action. | NoDelete() *EditableProTableW[T] |
OnDelete | OnDelete is called after a confirmed delete instead of removing the row from *rows (the app removes it, e.g. after a server call). | OnDelete(fn func(row T, index int)) *EditableProTableW[T] |
OnSave | OnSave receives a validated row (index -1 for a new row) before it is written back; call done from any goroutine. | OnSave(fn func(row T, index int, done func(error))) *EditableProTableW[T] |
Pagination | Pagination pages the rows locally, n per page. | Pagination(n int) *EditableProTableW[T] |
RowEditable | RowEditable limits which rows can be edited. | RowEditable(fn func(row T) bool) *EditableProTableW[T] |
RowKey | RowKey gives rows stable keys (needed when rows are inserted, deleted or reordered while one is edited; default: the row index). | RowKey(f func(T) string) *EditableProTableW[T] |
Save | Save validates the edited row k and writes it back (as its save action does; valid after Show). | Save(k string) |
Saved | Saved reports a row written back in the last Show. | Saved() bool |
ScrollX | ScrollX sets the table's scroll width. | ScrollX(w float32) *EditableProTableW[T] |
ScrollY | ScrollY bounds the table body to maxH (TableW.ScrollY): the header stays in place and only the visible rows are built, so many thousand rows stay fast. | ScrollY(maxH float32) *EditableProTableW[T] |
Show | Show builds the table. | Show() *EditableProTableW[T] |
Size | Size sets the density. | Size(s ControlSize) *EditableProTableW[T] |
Table | Table returns the inner table of the last Show. | Table() *TableW |
Title | Title sets the toolbar title. | Title(s string) *EditableProTableW[T] |
ToolBar | ToolBar adds actions at the right of the toolbar. | ToolBar(fn func()) *EditableProTableW[T] |
Validating | Validating reports async validations or a save in flight for row k. | Validating(k string) bool |
Virtual | Virtual is TableW.Virtual for the inner table: with ScrollY the body is windowed either way, Virtual states the intent (and takes the theme's Table V2 row height where it has one, as TableW.Virtual). | Virtual() *EditableProTableW[T] |
CellEditorTableW 方法
ui.CellEditorTableW:CellEditorTableW is an editable table that edits one cell at a time (Pro Components v3 CellEditorTable): double-click a cell of a column with an Editor (or press Enter on the keyboard-active cell) to edit it; Enter or moving focus away validates that cell and saves the row, Escape cancels and drops the draft. Only the edited column is validated. It is an EditableProTable preset (same editors, validation and OnSave flow), bordered and without pagination by default.
| 方法 | 说明 | 签名 |
|---|---|---|
Bordered | Bordered turns the cell borders on or off (default on). | Bordered(on bool) *CellEditorTableW[T] |
Cancel | Cancel leaves the edited cell without saving (as Escape does). | Cancel() |
Changed | Changed reports a change of *rows in the last Show. | Changed() bool |
Edit | Edit starts editing the cell of row key k in column col (valid after Show; ignored for a column without an Editor). | Edit(k, col string) |
EditingCell | EditingCell returns the row key and column key of the edited cell ("" when none). | EditingCell() (key, col string) |
Errors | Errors returns the validation messages of row k by column key. | Errors(k string) map[string]string |
ID | ID returns the widget ID (valid after Show). | ID() ID |
OnSave | OnSave receives the row with the validated cell applied before it is written back (see EditableProTableW.OnSave). | OnSave(fn func(row T, index int, done func(error))) *CellEditorTableW[T] |
Pagination | Pagination pages the rows locally, n per page (default: no pagination). | Pagination(n int) *CellEditorTableW[T] |
RowEditable | RowEditable limits which rows can be edited. | RowEditable(fn func(row T) bool) *CellEditorTableW[T] |
RowKey | RowKey gives rows stable keys (default: the row index). | RowKey(f func(T) string) *CellEditorTableW[T] |
Save | Save validates the edited cell and saves its row (as Enter does). | Save() |
Saved | Saved reports a row written back in the last Show. | Saved() bool |
ScrollX | ScrollX sets the table's scroll width. | ScrollX(px float32) *CellEditorTableW[T] |
ScrollY | ScrollY bounds the table body to maxH (EditableProTableW.ScrollY): only the visible rows are built. | ScrollY(maxH float32) *CellEditorTableW[T] |
Show | Show builds the table. | Show() *CellEditorTableW[T] |
Size | Size sets the density. | Size(s ControlSize) *CellEditorTableW[T] |
Table | Table returns the inner table of the last Show. | Table() *TableW |
Title | Title sets the toolbar title. | Title(s string) *CellEditorTableW[T] |
ToolBar | ToolBar adds actions at the right of the toolbar. | ToolBar(fn func()) *CellEditorTableW[T] |
Validating | Validating reports async validation or a save in flight for row k. | Validating(k string) bool |
Virtual | Virtual is TableW.Virtual for the inner table (see EditableProTableW.Virtual): with ScrollY the body is windowed either way; rows keep the height of the density (Size) unless the theme has a Table V2 row height (Element Plus). | Virtual() *CellEditorTableW[T] |
RowEditorTableW 方法
ui.RowEditorTableW:RowEditorTableW is an editable table that edits one whole row at a time (Pro Components v3 RowEditorTable): double-click a row (or press Enter on one of its cells) to edit every editable cell of it; Enter or moving focus out of the row validates all of its editors and saves, Escape cancels and drops the drafts (a new row is removed). It is an EditableProTable preset, bordered and without pagination by default.
| 方法 | 说明 | 签名 |
|---|---|---|
AddAtTop | AddAtTop puts new rows (and the add button) above the data. | AddAtTop() *RowEditorTableW[T] |
AddRow | AddRow adds a new draft row in edit mode and returns its key ("" when NewRow is not set or another row is being edited). | AddRow() string |
Bordered | Bordered turns the cell borders on or off (default on). | Bordered(on bool) *RowEditorTableW[T] |
Cancel | Cancel leaves row editing without saving (as Escape does). | Cancel() |
Changed | Changed reports a change of *rows in the last Show. | Changed() bool |
Edit | Edit starts editing the row with key k (valid after Show). | Edit(k string) |
EditingKey | EditingKey returns the key of the edited row ("" when none). | EditingKey() string |
Errors | Errors returns the validation messages of row k by column key. | Errors(k string) map[string]string |
ID | ID returns the widget ID (valid after Show). | ID() ID |
MaxLength | MaxLength hides the add button once there are n rows. | MaxLength(n int) *RowEditorTableW[T] |
NewRow | NewRow shows the "add a row" button (see EditableProTableW.NewRow); the new row opens in edit mode with focus in its first editor. | NewRow(fn func() T) *RowEditorTableW[T] |
OnSave | OnSave receives a validated row (index -1 for a new row) before it is written back (see EditableProTableW.OnSave). | OnSave(fn func(row T, index int, done func(error))) *RowEditorTableW[T] |
Pagination | Pagination pages the rows locally, n per page (default: no pagination). | Pagination(n int) *RowEditorTableW[T] |
RowEditable | RowEditable limits which rows can be edited. | RowEditable(fn func(row T) bool) *RowEditorTableW[T] |
RowKey | RowKey gives rows stable keys (default: the row index). | RowKey(f func(T) string) *RowEditorTableW[T] |
Save | Save validates the edited row and saves it (as Enter does). | Save() |
Saved | Saved reports a row written back in the last Show. | Saved() bool |
ScrollX | ScrollX sets the table's scroll width. | ScrollX(px float32) *RowEditorTableW[T] |
ScrollY | ScrollY bounds the table body to maxH (EditableProTableW.ScrollY): only the visible rows are built. | ScrollY(maxH float32) *RowEditorTableW[T] |
Show | Show builds the table. | Show() *RowEditorTableW[T] |
Size | Size sets the density. | Size(s ControlSize) *RowEditorTableW[T] |
Table | Table returns the inner table of the last Show. | Table() *TableW |
Title | Title sets the toolbar title. | Title(s string) *RowEditorTableW[T] |
ToolBar | ToolBar adds actions at the right of the toolbar. | ToolBar(fn func()) *RowEditorTableW[T] |
Validating | Validating reports async validation or a save in flight for row k. | Validating(k string) bool |
Virtual | Virtual is TableW.Virtual for the inner table (see EditableProTableW.Virtual): with ScrollY the body is windowed either way; rows keep the height of the density (Size) unless the theme has a Table V2 row height (Element Plus). | Virtual() *RowEditorTableW[T] |
ProColumn 参数类型
ui.ProColumn:ProColumn is a ProTable column over rows of type T.
| 字段 | 说明 | 类型 |
|---|---|---|
Key | string | |
Title | string | |
Width | float32 | |
MinWidth | float32 | |
Fixed | string | |
Align | TextAlign | |
Ellipsis | bool | |
Hidden | hidden until enabled in the column settings | bool |
ValueType | ValueType formats Value (see the Value* constants). | string |
ValueEnum | []ProEnum | |
Value | func(row T) any | |
Render | Render overrides the cell (i is the row index in the current page). | func(row T, i int) |
OnClick | OnClick makes link cells clickable. | func(row T) |
Currency | Currency is the ISO 4217 code ("USD", "JPY") or symbol of money cells (default: the Locale's, "¥" for zh-CN / ja, "$" for en-US, "NT$" for zh-TW). | string |
Editor | Editor makes the column editable in EditableProTable: the field (Required, Rules, Validate, AsyncValidate, Options, Min / Max ...) picks the control by its ValueType; Key, Label, ValueType and ValueEnum default to the column's. | *ProField |
Set | func(row *T, v any) | |
Sortable | server-side sort (reported in ProRequest.Sort) | bool |
Filterable | filter dropdown from ValueEnum (ProRequest.Filters) | bool |
HideInSearch | bool | |
HideInTable | bool |