[英]React-Hook-Form useFieldArray in React Native
我正在尝试在 react native 中使用带有 react-hook-form 的动态字段。 我最初尝试手动注册所有内容,但这不起作用。 然后我尝试使用 useFieldArray 钩子,但是所有新创建的字段都没有正确注册。 这是我的最新方法:
我有一个自定义组件来模仿 web 接口,用于反应原生 TextInput 并转发参考。
const Input = forwardRef((props, ref) => {
const {
onAdd,
...inputProps
} = props
return (
<View>
<TextInput
ref={ref}
{...inputProps} />
<Button onPress=(() => onAdd()} />
</View>
)
}
然后,我根据 useFieldArray 文档在我的表单中的显示方式使用此组件,但我有一个自定义更改处理程序。 我还明确设置了 ref 并尝试注册单个新字段。
const Inputs = useRef([])
const { control, register, setValue, handleSubmit, errors } = useForm({
defaultValues: {
test: defaultVals // this is an array of objects {title: '', id: ''}
}
})
{
fields.map((field, idx, arr) => (
<Input
key={field.id}
name={`test[${idx}]`}
defaultValue={field.name}
onChangeText={text => handleInput(text, idx)}
onAdd={() => append({title: '', id: ''})
ref={
e => register({ name: `test[${idx}]`
Inputs.curent[idx] = e
})
}
当我单击输入按钮时,它会按预期呈现一个新输入。 但是当我提交数据时,我只得到 defaultVals 值,而不是来自新输入的数据,尽管我确实有一个 object 代表test
数组中的输入。 输入的注册似乎有些问题,但我不能指望它。
如何正确设置 useFieldArray 或利用其他方式使动态字段与 react-hook-form 反应原生?
你可以像我一样尝试处理这个问题,使用每个元素和 1 个输入和这样的字段
<Controller
control={control}
name="username"
rules={{
required: {value: true, message: '* Please enter your username *'},
minLength: {value: 5, message: '* Account should be 5-20 characters in length! *'},
maxLength: {value: 20, message: '* Account should be 5-20 characters in length! *'},
pattern: {value: new RegExp(/^[a-zA-Z0-9_-]*$/), message: '* Invalid character *'},
}}
render={({onChange, value}) => (
<InputRegular
placeholder="username"
icon={{
default: images.iconUser,
focus: images.iconUser2,
}}
onChangeText={(val: string) => {
onChange(val);
setValue('username', val);
}}
value={value}
/>
)}
/>
处理提交与
const {register, errors, setValue, getValues, control, handleSubmit} = useForm<FormData>({
defaultValues: {
username: null,
email: null,
password: null,
rePassword: null,
},
mode: 'all',
});
useEffect(() => {
register('username');
register('email');
register('password');
register('rePassword');
}, [register]);
const onSubmit = async (data: any) => {
console.log('====================================');
console.log('data', data);
console.log('====================================');
if (getValues('username')) {
dispatch(
actionGetRegister({
data: {
username: getValues('username'),
email: getValues('email'),
password: getValues('password'),
secondaryPassword: getValues('secondaryPassword'),
},
}),
);
}
};
>
you can see my post for detail i use react-hook-form for react native
https://medium.com/@hoanghuychh/how-to-use-react-hook-form-with-react-native-integrate-validate-and-more-via-typescript-signup-244b7cce895b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.