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

问题描述 投票:1回答:1

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

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

我试图创建一个新的字符串播放器,每按一次“+ add”按钮就会添加+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)]
    ]
functional-programming textfield elm
1个回答
1
投票

正如错误消息所述,您将从函数返回类型String,该函数通过其类型签名返回Model。问题是这一行

  Clear ->
    model "Player" + 1

有点不清楚这是应该做什么的,但在上面的case表达式中,代码创建了一个新模型,它在其中进行更新content = newContent。如果要更新模型中的其他字段,则需要类似的模式。例如(不是100%确定语法,但你希望得到这个想法)

  Clear ->
    { model | currentNumber = currentNumber + 1 }
© www.soinside.com 2019 - 2024. All rights reserved.