右侧2个值的函数是什么意思?(型号 - > Html消息)

Moe*_*ler 12 elm

我在指南中遇到过:

viewValidation : Model -> Html msg
viewValidation model =
  let
    (color, message) =
      if model.password == model.passwordAgain then
        ("green", "OK")
      else
        ("red", "Passwords do not match!")
  in
    div [ style [("color", color)] ] [ text message ]
Run Code Online (Sandbox Code Playgroud)

所以这是一个功能,它需要Model. Html msg通常看起来像我们Html用参数调用函数msg.

msg但是,它似乎并没有在viewValidation函数的任何其他部分扮演任何角色.那么这是什么意思呢?在这种情况下它是什么意思?

mar*_*osh 14

Html Msg只是一个类型参数List Int.While List Int表示包含类型元素的列表Int,类似地Html Msg描述了一些可以处理/发出类型消息的HTML Msg.

例如,如果HTML中有一个按钮,它可能如下所示:

button [ onClick DoSomething ] [ text "caption" ]
Run Code Online (Sandbox Code Playgroud)

DoSomething这种Msg类型的情况在哪里.


Sim*_*n H 8

不要将类型定义与代码的正常执行混合在一起.Html它不是一个函数,它是一个带参数来定义视图函数类型的类型.

Html msgmsg一个变量本身最常见的定义,因此返回的Html与您当前使用的msg类型无关.这可能是因为它没有创建事件消息,或者因为视图函数将消息作为参数.

由于所建立的评论Html ()将是一种非常狭窄的类型,仅限于不返回任何内容.

最常见的情况是返回视图函数Html Msg- 即带有基于用户交互的消息的Html.

由于Elm鼓励组件化,您还需要Html.map牢记.它的类型签名是Html.map : (a -> b) -> Html a -> Html b.在组件的上下文中,这更容易理解为

Html.map : (Child.Msg -> Parent.Msg) -> Html Child.Msg -> Html Parent.Msg
Run Code Online (Sandbox Code Playgroud)

请注意,在父组件中定义消息时,您将具有以下内容:

type Msg = ChildMsg Child.Msg
Run Code Online (Sandbox Code Playgroud)

这意味着ChildMsg有类型签名:

ChildMsg : Child.Msg -> Parent.Msg
Run Code Online (Sandbox Code Playgroud)

所以我的视图功能有很多

parentView model = 
  -- childView model.child |> Html.map ChildMsg
  Html.map ChildMsg (childView model.child)
Run Code Online (Sandbox Code Playgroud)