【发布时间】:2020-11-18 17:08:49
【问题描述】:
使用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,这可能是由于重新渲染。
【问题讨论】:
标签: reactjs react-native react-final-form final-form