我有一个 Swift ui 视图,其中有一个儿童女巫从 @State 变量获取值。当我更新 @State 变量时,视图会重建,但子视图保持不变。
struct ContentView: View {
@State var msg: String = ""
var body: some View {
VStack {
Button(action: {
self.msg = "Hallo World"
}, label: { Text("Say Hallo")})
ChildView(msg: msg).padding().background(Color.orange)
Text(msg).padding().background(Color.green)
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ChildView: View {
@State var msg: String
var body: some View {
Text(msg)
}
}
Run Code Online (Sandbox Code Playgroud)