我正在编写一个Team Creator,用户可以在其中写下玩家的名字和他的力量。 (因此,假设用户写入10个玩家,则有5个团队,每个团队生成2个玩家。我不知道如何存储用户在输入中写入的值(由于当用户输入为空时,必须存储这些值)按下输入按钮以添加下一个播放器。)我已经初始化了变量和列表但是在存储值时我卡住了。
我现有的榆木代码:
import Browser
import Html exposing (Html, Attribute, button, text, h1, div, input, text)
import Html.Attributes exposing (style)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Player =
{ player : String
, strength : Int
}
type alias Model =
{ content : String
, teams : List Player
}
init : Model
init =
{ content = ""
, teams = []
}
-- UPDATE
type Msg
= Change String
update : Msg -> Model -> Model
update msg model =
case msg of
Change newContent ->
{ model | content = newContent }
-- VIEW
view : Model -> Html Msg
view model =
div []
[ h1 [style "font-family" "impact"] [ text "Team Creator" ]
, div[] [ input [ placeholder "🏅 Team 1", style "width" "300px", style "height" "30px", style "font-size" "25px", style "color" "#488aff"] [] ]
, input [ placeholder "💪🏼 Strength", style "width" "300px", style "height" "30px", style "font-size" "25px", style "color" "#32db64"] []
, div [] [ button [ style "background-color" "#66cc81", style "color" "white", style "margin-top" "20px", style "width" "300px", style "border-radius" "25px", style "height" "60px", style "font-size" "30px", style "margin-right" "70px"] [ text "+ADD" ] ]
]
在Elm中,如果你想捕获input
s的值,你需要为你关心的每个字段使用onInput
。每次字段更改时,这些都会向update
发送包含文本的消息。您最终会为每个字段创建一条消息,用新值更新您的model
。
然后,当用户单击要提交的按钮时 - 使用onClick
来处理 - update
函数应该转换并验证存储在model
中的那些值。如果他们是好的,将他们变成一个Player
并将其推入model.teams
列表!
从这里开始,您可以对其进行修改,以便在提交时或甚至实时提供有关错误的反馈。但要注重让上述工作先行!榆树的重构很便宜。
官方指南有一节关于the Elm Architecture以及buttons,text fields和forms如何在其中工作。这是一个很好的阅读,应该有希望澄清所有这些消息是如何发送出来并流经你的程序的。