【问题标题】:How to add the Selected attribute to a Select Option in Fable?如何将 Selected 属性添加到 Fable 中的 Select 选项?
【发布时间】:2026-01-31 14:25:05
【问题描述】:

我的页面上有一个选择标签:

open Fable.Helpers.React
open Fable.Helpers.React.Props

select [] 
       [
            option [ Value "a" ] [ str "a" ]
            option [ Value "b" ] [ str "b" ]
            option [ Value "c" ] [ str "c" ]
       ]

转译为:

<select>
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

现在,假设我希望“b”具有selected 属性。我试试:

option [ Value "b"; Selected true ] [ str "b" ]

HTML 中没有任何变化。而如果我例如试试:

option [ Value "b"; Disabled true ] [ str "b" ]

HTML 会相应改变:

<option value="b" disabled="">b</option>

那么如何处理“selected”属性呢?我需要得到:

<option value="b" selected="">b</option>

【问题讨论】:

    标签: html f# fable-f#


    【解决方案1】:

    根据@Foole 的建议,您需要使用Value 来设置所选项目。

    这是一个小代码,让您了解如何使用它并将其连接到 Elmish 程序中:

    type Model =
        { Selected : string }
    
    type Msg =
        | ChangeValue of string
    
    let init () = { Selected = "option-2" }, Cmd.none
    
    let update (msg:Msg) (model:Model) =
        match msg with
        | ChangeValue newValue ->
            { Selected = newValue }, Cmd.none
    
    let renderItem (key : string) (name : string) =
        option [ Value key ]
            [ str name ]
    
    let view model dispatch =
        select [ // Set the selected key
                 Value model.Selected
                 // Listen to `OnChange` event to update the `Model`
                 OnChange (fun ev ->
                    ChangeValue ev.target?value
                    |> dispatch
                 ) ]
            [ renderItem "option-1" "Apple"
              renderItem "option-2" "Pear"
              renderItem "option-3" "Orange" ]
    

    在@Foole 提出的代码中,您不能更改选择,因为Value "b" 是静态的,您不更新它。

    【讨论】:

    • 一个更有帮助的答案。这种方法解决了问题,太棒了!
    • 使用Feliz时,ev(Browser.Types.Event类型)需要Fable.Browser.Dom NuGet包。
    【解决方案2】:

    将其添加为“选择”元素的值:

       select [ Value "b" ] [
            option [ Value "a" ] [ str "a" ]
            option [ Value "b" ] [ str "b" ]
            option [ Value "c" ] [ str "c" ]
       ]
    

    【讨论】:

    • 嗯,不,看起来它不会更改 HTML。奇怪的是,当网页加载时,它选择了“b”,但现在我无法更改选择中的选择 - 它立即重置为此值。
    • 这就是 react 的工作原理。我建议要么学习更多关于 React 的知识,要么使用不同的视图引擎。