使用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}
/>
...
这似乎确实向前推进了裁判,但";"断裂";final-form
,每次击键都会忽略键盘,可能是由于重新渲染。
您没有转发来自FormInputGroup
的ref。
你需要在传下去的水平上捕捉裁判,并将其进一步转发给孩子们。应该是这样的:
const FormInputGroup = forwardRef(({ Component, validate, ...rest }, ref) => (
<Field ref={ref} component={Component} validate={validate} {...rest} />
))