Form
管理字段校验、提交与错误反馈。
实时预览
正在加载预览…
参数配置
全部字段 6
FormOptions
Go 代码
Go
// Inside a view; c is *ui.Context, t is nui.Theme.
// Keep s (example state) outside the view. See the complete example.
nui.Form(c.Key("form"), t, &s.Form, nui.FormOptions{Label: "Project form", Disabled: false, Validate: func(values nui.FormValues) nui.FormErrors {
if strings.TrimSpace(values["name"]) == "" {
return nui.FormErrors{"name": "Enter a project name"}
}
return nil
}, OnSubmit: func(values nui.FormValues) { s.Status = "Saved: " + values["name"] }}, func(t nui.Theme) {
nui.FormField(c.Key("field"), t, nui.FormFieldOptions{Name: "name", Value: s.Name, Label: "Project name", Required: true}, func(t nui.Theme) {
nui.Input(c.Key("name"), t, &s.Name, nui.InputOptions{Placeholder: "A new project"})
})
nui.Button(c.Key("submit"), t, "Save project", nui.ButtonOptions{}).OnClick(s.Form.Submit)
})
ui.Text(c, s.Status)使用说明
先提交空表单查看必填校验,再输入项目名并保存。FormState 持久保存注册字段与提交状态,Validate 返回按字段名映射的错误,OnSubmit 处理验证后的数据。
API 参考
Form
源码func Form(c *ui.Context, t Theme, s *FormState, o FormOptions, content func(Theme)) ui.ElementFormOptions
源码type FormOptions struct {
Label string
Disabled bool
Validate FormValidator
OnSubmit func(FormValues)
Decoration
}| 字段 | 类型 | 说明 |
|---|---|---|
Label | stringGo 零值: | 控件标签或可访问名称。 |
Disabled | boolGo 零值: | 禁用组件及其交互。 |
Validate | FormValidatorGo 零值: | 返回字段错误的表单校验函数。 |
OnSubmit | func(FormValues)Go 零值: | 提交表单或输入时通知应用的回调。 |
UI | StylesGo 零值: | 以部件名称为键覆盖外观和间距。 |
Style | func(Slot, ui.Element)Go 零值: | 同步配置当前构建的部件;不要保留 Element。 |
FormState
源码type FormState struct {
Fields map[string]*FormFieldState
Submitting bool
// contains filtered or unexported fields
}| 字段 | 类型 | 说明 |
|---|---|---|
Fields | map[string]*FormFieldStateGo 零值: | 以字段名称索引的表单状态。 |
Submitting | boolGo 零值: | 表单是否正在提交。 |