这个 `div` 调用产生:Html (String -> Msg) 但是 `view` 上的类型注释说它应该是:Html Msg

This `div` call produces: Html (String -> Msg) But the type annotation on `view` says it should be: Html Msg

我目前正在学习榆树,我只是偶然发现了这个问题,其中 div returns a Html (String -> Msg) 而不是 Html Msg .

我收到错误消息

div 调用产生:

Html (String -> Msg)

但是 view 上的类型注释说它应该是:

Html Msg
type alias Model =
   {
       firstNum: String,
       secondNum: String,
       answer: String
   }

init: Model 
init = { firstNum = "",
        secondNum = "",
        answer = ""}

type Msg =
    Add String| Minus String

update: Msg -> Model -> Model
update msg model =
    case msg of 
        Add  x -> { model | answer = x}
        Minus  y -> { model | answer = y}

view : Model -> Html Msg
view model =
    div [] 
    [
        input [ placeholder "Text to reverse", value model.firstNum] [],
        button [onClick Add] [text "add"],
        div [] [text model.answer]
    ]


main = 
  Browser.sandbox
  { init = init,
    update = update,
    view = view
  }

您将 Msg 类型定义为

type Msg =
    Add String| Minus String

with Add 采用 String 参数,但是当你在这里使用它时:

button [onClick Add] [text "add"],

你根本没有给它任何论据。

潜在的问题似乎是您对 Elm 架构的心理模型是错误的。您似乎将消息视为 "operations" 或函数调用而不是事件,其中 Add 是一个接受参数以应用于模型的函数。

您应该将消息视为对触发消息的描述。您可以将其称为 AddButtonClicked 而不是 Add String,不带任何参数(在本例中)。然后让更新函数根据模型中的内容做它应该做的事情,我猜这是对 firstNumsecondNum.

的算术运算

但是您也没有填充这些字段。为此,您需要使用 onInput 事件,该事件会请求一条带有 String 的消息。例如,您可以添加一条新消息 FirstNumChanged String,然后像这样将其与 input 一起使用:

input [ placeholder "Text to reverse", onInput FirstNumChanged, value model.firstNum] [],

我将留给您在 update 中解决如何处理它。