是否可以使用 ==
比较 Elm 中标记联合类型的构造函数,还是必须使用 case?
例子:
type alias Model =
{ accessToken : String
, page : Page
, config : Config
}
type Page
= Home String
| Profile String
menu : Model -> Html Msg
menu model =
div []
[ a [ href "#home", classList [ ("active", model.page == Home) ] ][ text "Home" ]
, a [ href "#profile", classList [ ("active", model.page == Profile)] ][ text "Profile" ]
]
在这个例子中,我想写一些类似 model.page == Home 的东西来检查当前页面是否是 Home,这样我就可以在那个链接上将 css 类设置为“事件”,但似乎我必须使用一个案例,我可以做,但在这种情况下实现有点尴尬。
最佳答案
不,您不能使用 ==
检查哪个构造函数用于创建标记联合值。我们通常这样做的方法是通过一些辅助函数:
isHome : Page -> Bool
isHome pg =
case pg of
Home _ -> True
_ -> False
isProfile : Page -> Bool
isProfile pg =
case pg of
Profile _ -> True
_ -> False
这导致调用时同样可读的代码:
menu : Model -> Html Msg
menu model =
div []
[ a [ href "#home", classList [ ( "active", isHome model.page ) ] ] [ text "Home" ]
, a [ href "#profile", classList [ ( "active", isProfile model.page ) ] ] [ text "Profile" ]
]
关于Elm 标记联合类型比较构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48884126/