无法在 React Final Form 中使用 forwardRef

Unable for forwardRef in React Final Form

使用 react-final-form 我无法 forwardRef 到我的 TextInput 用于 React Native。 ref 是处理键盘中的 Next 按钮和表单中其他强制聚焦事件所必需的。

我的设置如下 - 请注意,为简单起见,一些代码已被删除,因此不会进行剪切和粘贴。

// FormInputGroup/index.js

import React from 'react'
import PropTypes from 'prop-types'
import { Field } from 'react-final-form'

const FormInputGroup = ({ Component, validate, ...rest }) => (
  <Field component={Component} validate={validate} {...rest} />
)

FormInputGroup.propTypes = {
  name: PropTypes.string.isRequired,
  Component: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
  validate: PropTypes.oneOfType([PropTypes.array, PropTypes.func]),
}

export default FormInputGroup
// Form/index.js

import { Form } from 'react-final-form'
import { FormInputGroup, FormInputText, ButtonPrimary } from '/somewhere/'
...

const passwordInputRef = useRef()

<Form
  onSubmit={({ email, password }) => {
    // submit..
  }}
>
  {({ handleSubmit }) => (
    <>
      <FormInputGroup
        name="email"
        Component={FormInputText}
        returnKeyType="next"
        onSubmitEditing={() => passwordInputRef.current.focus()}
        blurOnSubmit={false}
      />
      <FormInputGroup
        name="password"
        Component={FormInputText}
        returnKeyType="go"
        onSubmitEditing={handleSubmit}
        ref={passwordInputRef} // <-- This does not work which i think is to be expected...
      />
      <ButtonPrimary loading={loading} onPress={handleSubmit}>
        Submit
      </ButtonPrimary>
    </>
  )}
</Form>

...
// FormInputText/index.js

const FormInputText = forwardRef( // <-- added forwardRef to wrap the component
  (
    {
      input,
      meta: { touched, error },
      label,
      ...
      ...rest
    },
    ref,
  ) => {
    return (
      <View style={styles.wrapper}>
        {label ? (
          <Text bold style={styles.label}>
            {label}
          </Text>
        ) : null}
        <View style={styles.inputWrapper}>
          <TextInput
            onChangeText={input.onChange}
            value={input.value}
            ...
            ref={ref}
            {...rest}
          />
        </View>
      </View>
    )
  },
)

我认为代码与 <FormInputGroup /> 组件有关。一个线索是,如果我将表单上的呈现更改为如下所示;

...

     <FormInputGroup
        name="password"
        Component={props => <FormInputText {...props} ref={passwordInputRef} />} // <-- changed
        returnKeyType="go"
        onSubmitEditing={handleSubmit}
      />

...

这似乎确实转发了 ref,但“中断”final-form 每次击键都会关闭键盘,大概是由于重新渲染。

您没有转发来自 FormInputGroup 的参考。

您需要在传递的级别捕获引用,并将其进一步转发给子级。应该是这样的:

const FormInputGroup = forwardRef(({ Component, validate, ...rest }, ref) => (
  <Field ref={ref} component={Component} validate={validate} {...rest} />
))