significado - Trabaja con elm y selecciona
ul 1741 español (5)
ACTUALIZACIÓN: onInput
funciona, vea otra respuesta a continuación con el código de trabajo 0.19: https://stackoverflow.com/a/41516493/540810
Sí, deberá usar para controlar el evento de cambio. Si miras la fuente de otros controladores de eventos integrados en Elm, como onClick
, verás que todos se crean utilizando la función on
.
Este es un ejemplo que utiliza targetValueIntParse de elm-community/html-extra para convertir el valor de cadena de la opción en un int.
Actualizado a 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 }
Puede ejecutar este ejemplo en el navegador https://runelm.io/c/ahz
Intento entender cómo funciona el olmo con un ejemplo personalizado.
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])
]
Es un ejemplo fácil de trabajar con un selecto. Me gustaría, cada vez que cambio el valor del mes, se multiplica a valor por 10, por ejemplo. De acuerdo con la documentación, no hay eventos como onChange
o onSelect
, ¿tengo que crear el mío con on ?
Aquí hay una actualización para Elm 0.19:
module Main exposing (main)
import Browser
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 =
Browser.sandbox { init = { duration = 1 }, view = view, update = update }
durationOption duration =
option [ value (String.fromInt duration) ] [ text (String.fromInt 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: " ++ (String.fromInt model.duration) ]
]
type Msg
= SetDuration Int
type alias Model =
{ duration : Int }
update msg model =
case msg of
SetDuration val ->
{ model | duration = val }
Esto funciona con Ellie en Elm 0.19.0: https://ellie-app.com/58wGf2YsR9Ya1
Código completo:
import Browser
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 =
Browser.sandbox { init = init, view = view, update = update }
init =
{ duration = 1 }
durationOption duration =
option [ value (String.fromInt duration) ] [ text (String.fromInt 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: " ++ (String.fromInt model.duration) ]
]
type Msg
= SetDuration Int
type alias Model =
{ duration : Int }
update msg model =
case msg of
SetDuration val ->
{ model | duration = val }
Para futuras referencias de Elm-newbies (como yo): con Elm 0.18.0 + elm-lang / html 2.0.0, el evento onInput
(ver código a continuación) works . (También note la diferencia en la notación de rango int ( List.range 0 12
lugar de [0..12]
).
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
-- MODEL
type alias Model =
{ duration : Int
}
model : Model
model =
Model 0
-- UPDATE
type Msg
= SetDuration String
update : Msg -> Model -> Model
update msg model =
case msg of
SetDuration s ->
let result =
String.toInt s
in
case result of
Ok v ->
{ model | duration = v }
Err message ->
model
-- VIEW
view : Model -> Html Msg
view model =
div []
[ select [ onInput SetDuration ]
(List.range 0 12 |> List.map intToOption)
, div [] [ text <| "Selected: " ++ (toString model.duration) ]
]
intToOption : Int -> Html Msg
intToOption v =
option [ value (toString v) ] [ text (toString v) ]
Un ejemplo con el controlador onInput
(también puede verificar el Ellie ):
module Main exposing (main)
import Browser import Html exposing (Html, button, div, text, select, option) import Html.Attributes exposing (value, selected) import Html.Events exposing (onInput) import Dict exposing (Dict)
type alias Model =
{ options : Dict Int (String, Bool)
}
initialModel : Model initialModel =
{ options = Dict.fromList [(0, ("All time", False)), (1, ("One week", True)), (2, ("24h", False))]
}
type Msg
= Select String
update : Msg -> Model -> Model update msg model =
case msg of
Select value ->
case String.toInt value of
Just selectedID ->
let
changeSelection id (label, _) =
if id == selectedID then
(label, True)
else
(label, False)
in
{model | options = Dict.map changeSelection model.options}
Nothing ->
model
view : Model -> Html Msg view model =
let
toOption (id, (label, isSelected)) =
option [value (String.fromInt id), selected isSelected] [text label]
in
div []
[ select [onInput Select] (List.map toOption <| Dict.toList model.options)
, div [] [text "DEBUG"]
, div [] [text <| Debug.toString model.options]
]
main : Program () Model Msg main =
Browser.sandbox
{ init = initialModel
, view = view
, update = update
}