Why is the value of the interface not updated after clearing the bound value in app.input?
Author: jinguihuaCreated Jul 30, 2025Updated Jul 30, 2025
代码如下
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")
}),
)
}
Source: maxence-charriere/go-app