如何在文本字段中删除和输出新字符串?

时间:2019-02-19 22:20:01

标签: functional-programming textfield elm

我想清除文本字段,并想在按下按钮时创建一个新的占位符。另外,我希望在占位符中增加一个增量,以计数创建的每个新文本字段(播放器1,播放器2,播放器3等),我尝试使用elm文档中的“增加”按钮。但是我得到一个错误:

Something is off with the 5th branch of this `case` expression:

78|       model "Player" + 1
          ^^^^^^^^^^^^^^^^^^
The 5th branch is:

    number

But the type annotation on `update` says it should be:

    Model

我试图创建一个新的字符串播放器,每次按+1时都会添加。因此,使用onClick事件+名称(清除),还可以在文档中完成该操作。

这是我的榆木代码:

--imports
...

-- MAIN


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



-- MODEL
type alias Player =
  { player : String
  , strength : Int
  , number : Int
  }


type alias Model =
  { content : String
  , teams : List Player
  , currentNumber : Int
  , currentPlayer : String
  , currentStrength : Int
  }





init : Model
init =
  { content = ""
  , teams = []
  , currentNumber = 0
  , currentPlayer = ""
  , currentStrength = 0
   }



-- UPDATE


type Msg
  = Change String
  | Clear



update : Msg -> Model -> Model
update msg model =
  case msg of
    Change newContent ->
      { model | content = newContent }

    Clear ->
      model "Player" + 1

-- VIEW

view : Model -> Html Msg
view model =
  div []
    [ h1 [style "font-family" "impact"] [ text "Team Creator" ]
    ,  h2 [style "font-family" "impact"] [ text "Name and Strength:" ]
    , div[] [ input [ placeholder  " Player 1", style "width" "300px"] [] ]
    , input [ placeholder  " Strength", style "width" "300px"] []
    , div [] [ button [ style "background-color" "#66cc81", style "color" "white", onClick Clear] [ text "+ADD" ] ]
    ,  h2 [style "font-family" "impact"] [ text "Teams:" ]
    , div [] [ text (model.currentPlayer)]
    ]

1 个答案:

答案 0 :(得分:1)

错误消息指出,您正在从通过其类型签名返回String的函数返回类型Model。问题是这条线

  Clear ->
    model "Player" + 1

目前尚不清楚该做什么,但是在上面的情况表达式中,代码创建了一个新模型,在该模型中进行更新content = newContent。如果要更新模型中的其他字段,则需要类似的模式。例如(不确定100%的语法,但希望您会明白这一点)

  Clear ->
    { model | currentNumber = currentNumber + 1 }