NavigationLink 101:如何从宿主发送数据到副View?

NavigationLink 101: How to send data from the host to the secondary View?

目标: 只需通过 NavigationLink 将每个列表行的 struct 传递给辅助视图。

Baby Step(先前目标):仅将字符串数组的成员传递给辅助视图。

问题: 辅助视图期望参数调用中的 Binding-String 值与 闭包字符串 上下文中的值。

所以我必须在调用之前将 @State var 设置为 current/context 值。

这是我的问题。我不能简单地将绑定变量等同于当前上下文变量;因为在 SwiftUI 中,此类语句仅限于基于视图的内容。

这行不通:

这是实际的代码:

import SwiftUI
  
struct ContentView: View {
    @State var name = ""   //... load with inital value to avoid having to add a call parameter.
    
    var body: some View {
        let myArray = ["Larry", "Moe", "Curly"]
        NavigationView {
            List(myArray, id: \.self) { theStooge in
                NavigationLink(destination: SecondView(stoogeName: theStooge)) {
                    Text(theStooge)
                }
            }
            .navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct SecondView: View {
    @Binding var stoogeName: String
    var body: some View {
        Text("Hello \(name)")
    }
}

我只能通过 NavigationLink 的目标参数中的 Text("Hello World") 创建 SecondView。但这不是很有帮助。我想将数据(数据结构)传递给每个列表成员的辅助视图。

但是我需要设置一个绑定变量。 如何?
我是否必须陪审团装配 EnvironmentObject 或 Singleton?

绑定可以设置为动态 属性 但您的数组是常量局部变量。这是使用绑定的可能解决方案:

struct ContentView: View {
    @State var name = ""   //... load with inital value to avoid having to add a call parameter.
    
    @State private var myArray = ["Larry", "Moe", "Curly"]

    var body: some View {
        NavigationView {
            List(myArray.indices, id: \.self) { index in
                NavigationLink(destination: SecondView(stoogeName: $myArray[index])) {
                    Text(myArray[index])
                }
            }
            .navigationBarTitle("Three Stooges").navigationBarTitleDisplayMode(.inline)
        }
    }
}