Как вы создаете Ref в Suave Fable? - PullRequest
1 голос
/ 08 мая 2019

У меня есть текстовый ввод, и мне удалось отменить ввод.Однако мой слушатель нажатия клавиш не будет ожидать сброса событий ввода текста перед обработкой клавиши ввода, которая закончит редактирование без получения последнего значения в неуправляемом компоненте.

Поскольку я нахожусь в веб-пакете, 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.

Ответы [ 2 ]

0 голосов
/ 14 мая 2019

Как оказалось, для того, что мне было нужно, рефери не были нужны, однако я все-таки получил.

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 []
0 голосов
/ 11 мая 2019

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 "..." ]
...