How to get style in Elm

試著忘記壹切 提交于 2019-12-12 15:36:39

问题


I'm starting with Elm and when you want to set style you can simply embed it on your component: Html.Attribute.style List (String, String)

But I can't find a way to get the style instead of set. What I need, actually, is the line-height (CSS attribute) of a specifc Html msg. I read a little about using a custom decoder (with Json.Decode.at) but I still didn't get it.


回答1:


Mateus, I'm just starting w/ elm so take this for what it's worth.

When you receive an event you can interrogate the event target to get information about it, or a relative element. Apparently, absent an event there isn't (currently) a way to "reach into" the DOM at pull out values willy-nilly (see *1 below)

Resources:

*1: https://medium.com/@debois/elm-the-dom-8c9883190d20

*2: https://robots.thoughtbot.com/building-custom-dom-event-handlers-in-elm

Back to your question, turns out what's set as style [(key1, val1)...(keyn, valn)] gets turned into {key1:val1, ...keyn:valn}. (I find this by debugging elm's transpiled code ... then see documentation elsewhere about it; go figure.)

See below to get line-height specifically. I suppose it could be more useful to get a list of all styles. Revised sample follows:

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (on)
import Json.Decode 


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

type Msg = Attr StyleStruct

type alias StyleStruct =
  {lineHeight: String}


view model =
  div []
    [ button [ id "btn"
        , class "cls"
        , style [("color", "green"), ("line-height", "3em")]
        , myOnClick Attr ]
        [ text "Show line-height" ]
    , div [] [ text ("(" ++ model ++ ")")]
    ]

update msg model =
  case msg of
    Attr v1 ->
      toString v1

targetStyle =
  Json.Decode.map StyleStruct
    (Json.Decode.at ["target", "style"] styleStructDecoder)

styleStructDecoder =
  Json.Decode.at ["line-height"] Json.Decode.string


myOnClick : (StyleStruct -> msg) -> Html.Attribute msg
myOnClick tagger =
  on "click" (Json.Decode.map tagger targetStyle)


来源:https://stackoverflow.com/questions/43398381/how-to-get-style-in-elm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!