来自 React 背景,如果定义了值,则很容易仅呈现视图。它看起来像这样:
function Component ({ profile }) {
return (
<div>{profile && <div>{profile.name}}</div>
)
}
Run Code Online (Sandbox Code Playgroud)
但我发现在 SwiftUI 中复制这种模式要困难得多。理想情况下,我们可以在我们的视图中使用条件展开,但这目前不起作用。我能想出的唯一解决方案真的很不优雅:
function Component ({ profile }) {
return (
<div>{profile && <div>{profile.name}}</div>
)
}
Run Code Online (Sandbox Code Playgroud)
有没有人有一些更好的策略来使用可选值进行条件渲染?
您可以反过来使用map来处理可选的,如下所示:
struct ProfileView : View {
var profile: Profile?
var body : some View {
profile.map { Text("profile: \($0.bio)") }
}
}
Run Code Online (Sandbox Code Playgroud)
(在这个例子中$0是你解开的profile。)
如果您需要 else 情况:
profile.map { Text($0.bio) } ?? Text("Not available")
Run Code Online (Sandbox Code Playgroud)
只需这样做:
struct LayoutView : View {
@State var profile: Profile?
var body : some View {
Group {
if profile != nil {
ProfileView(profile: profile!)
}
}
}.onAppear(perform: fetch)
// fetch method
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5205 次 |
| 最近记录: |