扩展Elm教程表单应用程序以包含编号输入Age

前端之家收集整理的这篇文章主要介绍了扩展Elm教程表单应用程序以包含编号输入Age前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在关注这个教程: http://guide.elm-lang.org/architecture/user_input/forms.html

那里的文字对我有意义,我的问题与它在页面底部列出的练习有关.它问我:

“Add an additional field for age and check that it is a number.”

我对此有困难,因为onInput函数似乎只接受String输入.我觉得奇怪的是没有等效的type =“number”输入.

然而,这是我的尝试不起作用:

  1. import Html exposing (..)
  2. import Html.App as Html
  3. import Html.Attributes exposing (..)
  4. import Html.Events exposing (onInput)
  5. import String exposing (length)
  6.  
  7. main =
  8. Html.beginnerProgram { model = model,view = view,update = update }
  9.  
  10.  
  11. -- MODEL
  12.  
  13. type alias Model =
  14. { name : String,password : String,passwordAgain : String,age : Int
  15. }
  16.  
  17.  
  18. model : Model
  19. model =
  20. Model "" "" "" 0
  21.  
  22.  
  23. -- UPDATE
  24.  
  25. type Msg
  26. = Name String
  27. | Password String
  28. | PasswordAgain String
  29. | Age Int
  30.  
  31. update : Msg -> Model -> Model
  32. update msg model =
  33. case msg of
  34. Name name ->
  35. { model | name = name }
  36.  
  37. Password password ->
  38. { model | password = password }
  39.  
  40. PasswordAgain password ->
  41. { model | passwordAgain = password }
  42.  
  43. Age age ->
  44. { model | age = age }
  45.  
  46.  
  47. -- VIEW
  48.  
  49. view : Model -> Html Msg
  50. view model =
  51. div []
  52. [ input [ type' "text",placeholder "Name",onInput Name ] [],input [ type' "password",placeholder "Password",onInput Password ] [],placeholder "Re-enter Password",onInput PasswordAgain ] [],input [ type' "number",placeholder "Age",onInput Age ] [],viewValidation model
  53. ]
  54.  
  55. viewValidation : Model -> Html msg
  56. viewValidation model =
  57. let
  58. (color,message) =
  59. if model.password /= model.passwordAgain then
  60. ("red","Passwords do not match!")
  61. else if length model.password <= 8 then
  62. ("red","Password must be more than 8 characters!")
  63. else
  64. ("green","OK")
  65. in
  66. div [ style [("color",color)] ] [ text message ]

我得到的错误如下:

  1. -- TYPE MISMATCH ----------------------------------------------------- forms.elm
  2.  
  3. The argument to function `onInput` is causing a mismatch.
  4.  
  5. 58| onInput Age
  6. ^^^
  7. Function `onInput` is expecting the argument to be:
  8.  
  9. String -> a
  10.  
  11. But it is:
  12.  
  13. Int -> Msg

注意:我知道我可以创建Age输入作为另一个文本输入,但练习特别要求我检查它是一个`数字类型.我认为这意味着我应该将它作为Int保存在模型中.

我很清楚错误是什么.我只是想知道在Elm中解决这个问题的惯用方法.谢谢.

解决方法

来自onInput事件的任何用户输入都是String.

您的模型期望它是一个Int

使用String.toInt从字符串值中解析整数值.

调整更新功能以将类型转换为Int并将类型签名更改为Age String

  1. Age age ->
  2. case String.toInt age of
  3. Ok val ->
  4. { model | age = val }
  5.  
  6. -- Notify the user,or simply ignore the value
  7. Err err ->
  8. model

这样您就可以选择通知用户有关错误的信息.

如果Maybe值更适合你,整个语句可以简化为:

  1. Age age ->
  2. { model | age = Result.toMaybe (String.toInt age) }

猜你在找的HTML相关文章