如何将 Selected 属性添加到 Fable 中的 Select 选项?
How to add the Selected attribute to a Select Option in Fable?
我的页面上有一个 select 标签:
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>
将其添加为 "select" 元素的值:
select [ Value "b" ] [
option [ Value "a" ] [ str "a" ]
option [ Value "b" ] [ str "b" ]
option [ Value "c" ] [ str "c" ]
]
根据@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"
是静态的,您不会更新它。
我的页面上有一个 select 标签:
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>
将其添加为 "select" 元素的值:
select [ Value "b" ] [
option [ Value "a" ] [ str "a" ]
option [ Value "b" ] [ str "b" ]
option [ Value "c" ] [ str "c" ]
]
根据@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"
是静态的,您不会更新它。