使用榆木并选择 [英] Work with elm and select

查看:42
本文介绍了使用榆木并选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了解Elm如何与自定义示例一起使用。

I try to understand how elm works with a custom example.

durationOption duration =
  option [value (toString duration) ] [ text (toString duration)]

view : Model -> Html Msg
view model =
  Html.div []
    [ h2 [] [ text "Month selector"]
    , select []
      (List.map durationOption [1..12])    
    ]

这是一个使用select的简单示例。我想,例如,每次更改月份值时,它都会乘以10。根据文档,没有诸如 onChange onSelect 之类的事件,我是否必须使用

It's an easy example to work with a select. I would like, each time I change the month value it multiplies to value by 10 for example. According to the documentation there is not events like onChange or onSelect, do I have to create mine with on ?

推荐答案

更新: onInput 可行,请参见下面的另一个答案,其中包含0.19工作代码: https://stackoverflow.com/a/41516493/540810

UPDATE: onInput works, see another answer below with 0.19 working code: https://stackoverflow.com/a/41516493/540810

是的,您需要使用 on 来处理更改事件。如果您查看其他事件处理程序的来源内置于Elm中,例如 onClick ,您会看到它们都是使用 on 函数构建的。

Yes, you will need to use on to handle the change event. If you look at the source for other event handlers built into Elm, like onClick, you'll see that they are all built using the on function.

以下是使用 targetValueIntParse 来自 elm-community / html-extra 用于将选项中的字符串值转换为int。

Here's an example that is using targetValueIntParse from elm-community/html-extra for turning the string value from the option into an int.

已更新为Elm-0.18

Updated to Elm-0.18

import Html exposing (..)
import Html.Events exposing (on)
import Html.Attributes exposing (..)
import Json.Decode as Json
import String
import Html.Events.Extra exposing (targetValueIntParse)


main =
    beginnerProgram { model = { duration = 1 }, view = view, update = update }


durationOption duration =
    option [ value (toString duration) ] [ text (toString duration) ]


view : Model -> Html Msg
view model =
    Html.div []
        [ h2 [] [ text "Month selector" ]
        , select [ on "change" (Json.map SetDuration targetValueIntParse) ]
            (List.map durationOption (List.range 1 12))
        , div [] [ text <| "Selected: " ++ (toString model.duration) ]
        ]


type Msg
    = SetDuration Int


type alias Model =
    { duration : Int }


update msg model =
    case msg of
        SetDuration val ->
            { model | duration = val }

您可以在浏览器 https://runelm.io/c/ahz

这篇关于使用榆木并选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆