简体   繁体   中英

React-Hook-Form useFieldArray in React Native

I am trying to utilize dynamic fields with react-hook-form in react native. I initially tried to manually register everything, but that doesn't work. Then I tried to use the useFieldArray hook, but all the newly created fields don't register correctly. Here is my latest approach:

I have a custom component to mimic the web interface for a react native TextInput and forward the ref.

const Input = forwardRef((props, ref) => {
  const {
    onAdd,
    ...inputProps
  } = props

  return (
    <View>
      <TextInput
       ref={ref}
       {...inputProps} />
      <Button onPress=(() => onAdd()} />
    </View>
  )
}

I then use this component according to how the useFieldArray docs show in my form except that I have a custom change handler. I also set the ref explicitly and attempt to register the individual new field.

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
      })
}

When I click the button for the input it renders a new input as would be expected. But when I submit the data, I only get the defaultVals values and not the data from the new input, though I do have an object that represents that input in the test array. It seems something is off with the registering of the inputs, but I can't put my finger on it.

How do I properly set up useFieldArray or utilize other ways to have dynamic fields in react native with react-hook-form?

you can try handle this problem like me, use each element with 1 input and field like this

 <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}
        />
      )}
    />

handleSubmit with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM