让单选按钮反映模型

Having radio buttons reflect the model

this example中,初始的fontSizeMedium。这反映在字体的大小上,但没有选择中号单选按钮。有没有办法让单选按钮始终反映当前 fontSize?

这是有问题的代码:

view : Model -> Html Msg
view model =
  div []
    [ fieldset []
        [ radio "Small" (SwitchTo Small)
        , radio "Medium" (SwitchTo Medium)
        , radio "Large" (SwitchTo Large)
        ]
    , Markdown.toHtml [ sizeToStyle model.fontSize ] model.content
    ]


radio : String -> msg -> Html msg
radio value msg =
  label
    [ style [("padding", "20px")]
    ]
    [ input [ type_ "radio", name "font-size", onClick msg ] []
    , text value
    ]

这是用于呈现无线电输入的行:

input [ type_ "radio", name "font-size", onClick msg ] []

收音机有一个 checked 属性 (see the docs),看来您可以根据当前字体大小添加它?类似于:

radio : String -> Bool -> msg -> Html msg
radio value isChecked msg =
  label
    [ style [("padding", "20px")]
    ]
    [ input [ type_ "radio", name "font-size", checked isChecked, onClick msg ] []
    , text value
    ]

…然后根据模型在view函数中设置isChecked参数。

这是您要找的吗?

view : Model -> Html Msg
view model =
  div []
    [ fieldset []
        [ radio "Small" (model.fontSize == Small) (SwitchTo Small)
        , radio "Medium"(model.fontSize == Medium)  (SwitchTo Medium)
        , radio "Large" (model.fontSize == Large) (SwitchTo Large)
        ]
    , Markdown.toHtml [ sizeToStyle model.fontSize ] model.content
    ]


radio : String -> Bool > msg -> Html msg
radio value isChecked msg =
  label
    [ style [("padding", "20px")]
    ]
    [ input [ type_ "radio", name "font-size", onInput msg, checked isChecked ] []
    , text value
    ]

请注意,我将 onClick 更改为 onInput,我认为这是表单选择的更好做法。

顺便说一句,我倾向于将 msg 参数放在类型签名的开头,因为它最不可能成为函数管道的一部分:

radio : msg -> Bool -> String -> Html msg