2016-09-07 3 views
4

다음 코드를 사용하여 elm 앱에서 간단한 드롭 다운을 렌더링하고 싶지만 예상대로 작동하지 않습니다. 가능하다면 공용체 역할을 유지하고 문자열 사용을 피하고 싶습니다.Elm lang의 select (dropdown) 태그 사용 방법

느릅 나무에서 드롭 다운을 사용하는 가장 좋은 방법은 무엇입니까? 나는 아직 어떤 예도 찾지 못했다.

import Html exposing (..) 
import Html.App exposing (beginnerProgram) 
import Html.Events exposing (..) 
import Html.Attributes exposing (..) 
import Json.Decode 

main = 
    beginnerProgram 
    { model = initialModel 
    , view = view 
    , update = update 
    } 

initialModel = 
    { role = None 
    } 

type Role 
    = None 
    | Admin 
    | User 

type alias Model = 
    { role: Role 
    } 

type Msg 
    = SelectRole Role 


update msg model = 
    case msg of 
    SelectRole role -> 
     { model | role = role } 


view : Model -> Html Msg 
view model = 
    div 
    [] 
    [ select 
     [ ] 
     [ viewOption None 
     , viewOption Admin 
     , viewOption User 
     ] 
    , pre [] [ text <| toString model ] 
    ] 



viewOption : Role -> Html Msg 
viewOption role = 
    option 
    [ onClick (SelectRole role) ] 
    [ text <| toString role ] 

답변

5

onClick 핸들러는 정말 option 요소와 작동하지 않습니다. 대신 change 이벤트를 캡처하고 JSON targetValue을보고 선택한 항목을 확인하십시오.

내가 먼저 onClick 핸들러를 제거하고 대신 option 태그의 value 속성을 설정합니다 :

viewOption : Role -> Html Msg 
viewOption role = 
    option 
    [ value <| toString role ] 
    [ text <| toString role ] 

지금 당신이 이벤트의 targetValue 문자열을하고 Role로 변환 할 수있는 JSON 디코더가 필요합니다을 :

targetValueRoleDecoder : Json.Decode.Decoder Role 
targetValueRoleDecoder = 
    targetValue `Json.Decode.andThen` \val -> 
    case val of 
     "Admin" -> Json.Decode.succeed Admin 
     "User" -> Json.Decode.succeed User 
     "None" -> Json.Decode.succeed None 
     _ -> Json.Decode.fail ("Invalid Role: " ++ val) 

이제는 그 번호를 select에 추가하면됩니다.이벤트 핸들러 :

[ select 
     [ on "change" (Json.Decode.map SelectRole targetValueRoleDecoder) 
     ] 
     [ viewOption None 
     , viewOption Admin 
     , viewOption User 
     ] 

우리가 문자열에 의지해야한다는 사실은 단지 유효한 조합 유형으로 DOM 이벤트에서 값을 변환해야하는 유물이다. 당신은 여전히 ​​유니온 타입으로 Role을 유지하려고합니다. Elm은 어떠한 종류의 자동 String to Union Type 함수도 지원하지 않기 때문에 각 union 유형을 대상으로 JSON 디코더를 만들어야합니다.

+0

굉장한 사람. 좋은 설명에 감사드립니다. –