2

我有一个文本输入,我已经设法消除输入。但是,我的按键侦听器不会等待文本输入事件刷新,然后再处理 enter 键,这将结束编辑而不会在不受控制的组件中获取最新值。

由于我在 webpack 中,React...未定义所以我不能只是React.createRef()当前源代码显示该函数存在https://github.com/fable-compiler/fable-react/blob/e904add886bab45003c074cd2b06b8834fddf65b/src/Fable.React.Helpers .fs#L366

但是它不能解析/编译。 paket.lock显示 Fable.React 4.1.3,Fable.Elmish.React 2.1。

4

2 回答 2

3

createRef仅从 5.x 版本开始可用,因此您需要更新到最新版本。可以肯定的是,我鼓励您在撰写本文时升级到最新版本5.2.3

这意味着您需要将您的应用程序升级到 Fable.Core v3,您可以在此处了解更多信息。

完成后,您可以createRef这样使用:

open Fable.React
open Fable.React.Props

type MapComponent(initProps) =
    inherit Fable.React.Component<MapComponentProps, obj>(initProps)

    let mapRef : IRefHook<Browser.Types.HTMLDivElement option> = createRef None

    override this.render() =
        div [ RefValue mapRef ]
            [ str "..." ]
于 2019-05-11T20:16:30.623 回答
0

事实证明,对于我所需要的,裁判不是必需的,但我确实得到了一个。

type IReactRef =
  inherit Browser.Element

[<Emit("React.createRef")>]
let createRef(): IReactRef = jsNative

type TextInputProps =
  { Ident: string
    Delay: int
    AddedAttributes: IHTMLProp list
    DefaultValue: string option
    OnChange: (string -> unit)
    OnEscape: (unit -> unit) option
    OnEnter: (string -> unit) option
  }

type TextInputState = InputState
let textInputDelayDefault = 500
type TextInputComponent(props) =
  inherit React.Component<TextInputProps, TextInputState>(props)
  let mutable textInput: obj = null
  let debouncer = Eventing.Debouncer<string>.Create props.Ident props.Delay

  do
    textInput <- react.createRef()
    base.setInitState InputState

  member __.TextInput: IReactRef option =
    textInput
    |> Option.ofObj
    |> Option.map unbox

  // provide cancel edit extension point (Escape doesn't fire keypress)
  member this.OnKeyUp(e: React.KeyboardEvent) =
    if e.key = "Escape" then
      match this.props.OnEscape with
      | Some f ->
        e.preventDefault()
        f()
      | None -> ()

  // provide finish edit extension point
  member this.OnKeyPress(e: React.KeyboardEvent) =
    let value =
      e
      |> unbox
      |> Eventing.getTargetValue
    if e.key = "Enter" then
      this.props.OnEnter
      |> Option.iter (fun f ->
           e.preventDefault()
           debouncer.Clear()
           // send the current value in case the onChange did not send the current value due to debouncing
           f value)

  override this.render() =
    let r =
      input [ yield R.Props.Ref(unbox textInput)
              yield R.Props.OnKeyPress this.OnKeyPress
              yield R.Props.OnKeyUp this.OnKeyUp
              yield Eventing.onDebChange debouncer this.props.OnChange
              yield R.Props.DefaultValue(this.props.DefaultValue |> Option.defaultValue "")
              yield! this.props.AddedAttributes ]
    r

let inline textInputComponent props = Fable.Helpers.React.ofType<TextInputComponent, _, _> props []
于 2019-05-14T13:13:05.617 回答