关于elm:在右边有2个值的函数是什么意思? (型号-> HTML味精)


What does a function with 2 values on the right side mean? (Model -> Html msg)

我在指南中遇到了这个问题:

1
2
3
4
5
6
7
8
9
10
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 ]

这是一个使用Model的函数。
Html msg在我看来通常就像我们正在使用参数msg调用函数Html一样。

但是,

msgviewValidation函数的任何其他部分似乎都没有扮演任何角色。那么这意味着什么,在这种情况下又意味着什么呢?


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

例如,如果您的HTML中有一个按钮,则它可能看起来像这样:

1
button [ onClick DoSomething ] [ text"caption" ]

DoSomethingMsg类型的情况。


请勿将类型定义与常规代码执行混合使用。 Html不是函数,它是一种带参数的类型,用于定义视图函数的类型。

Html Msg是您可以拥有的最通用的定义,因为Msg本身是变量,因此它返回的Html与当前使用的msg类型无关。这可能是因为它不创建任何事件消息,或者是由于view函数将消息作为参数。

由于建立的注释Html ()将是一个非常狭窄的类型,被限制为不返回任何内容。

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

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

1
Html.map : (Child.Msg -> Parent.Msg) -> Html Child.Msg -> Html Parent.Msg

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

1
type Msg = ChildMsg Child.Msg

表示ChildMsg具有类型签名:

1
ChildMsg : Child.Msg -> Parent.Msg

所以我的视图函数有很多

1
2
3
parentView model =
  -- childView model.child |> Html.map ChildMsg
  Html.map ChildMsg (childView model.child)