Skip to content

Why is the value of the interface not updated after clearing the bound value in app.input? #1083

@jinguihua

Description

@jinguihua

代码如下

type Hello struct {
app.Compo
name string
inputRev int // 用来强制重建 input 节点
}

func (self *Hello) Render() app.UI {
fmt.Println("render11 :", self.name)

return app.Div().Body(
	app.Input().
		// 关键点:ID 带上 inputRev,清空时递增 -> 旧节点被卸载,新节点是空的
		ID(fmt.Sprintf("name-%d", self.inputRev)).
		AutoComplete(false).
		Value(self.name).
		OnInput(self.ValueTo(&self.name)), // ✅ 用 OnInput 实时同步,避免失焦回写

	app.Button().
		Text("Clear").
		OnClick(func(ctx app.Context, e app.Event) {
			ctx.Dispatch(func(ctx app.Context) { // ✅ 所有状态修改放进 Dispatch
				self.name = ""  // 清空受控值
				self.inputRev++ // 🔁 强制重建输入框节点,避免聚焦时 DOM 保留旧值
			})
			fmt.Println("clear")
		}),
)

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions