简体   繁体   English

从reach-hook-form中的单选按钮获取值

[英]Getting values from radio buttons in reach-hook-form

I am learning to code in React and Next.js and when it comes to submitting data in forms is really easy with react-hook-forms, but when it comes to radio buttons I am struggling a bit.我正在学习在 React 和 Next.js 中编码,当涉及到在 forms 中提交数据时,使用 react-hook-forms 真的很容易,但是当涉及到单选按钮时,我有点挣扎。 I have a step in my app that I need to select one option between 3, and I am using radio buttons to do this.我的应用程序中有一个步骤,我需要 select 3 之间的一个选项,我正在使用单选按钮来执行此操作。

The code I am using here, returns paymentMethod: PayPal, no matter which option I select from all the radio buttons, I always get that.我在这里使用的代码返回paymentMethod:PayPal,无论我从所有单选按钮中选择哪个选项我select,我总是得到那个。

/** @format */

import React, { useContext, useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import Cookies from 'js-cookie';
import { Store } from '../utils/Store';
import Layout from '../components/Layout';
import Main from '../components/ui/Main/Main';
import HeadlineThree from '../components/ui/Type/HeadlineThree/HeadlineThree';
import { Controller, useForm } from 'react-hook-form';
import Section from '../components/ui/Section/Section';
import Button from '../components/ui/Button/Button';

export default function Payment() {
  // iniciamos el formulario
  const {
    handleSubmit,
    control,
    setValue,
    getValues,
    formState: { errors },
  } = useForm();

  // levantamos el router para redirigir
  const router = useRouter();

  // useState de paymentMethods
  const [paymentMethod, setPaymentMethod] = useState('');

  // alcanzamos el Store
  const { state, dispatch } = useContext(Store);

  // pediremos los states
  const {
    cart: { shippingAddress },
  } = state;

  // comprobaremos si tiene address y si la tiene, el método de pago
  useEffect(() => {
    if (!shippingAddress.address) {
      router.push('/shipping');
    } else {
      setPaymentMethod(Cookies.get('paymentMethod') || '');
    }
  }, []);
  // handler del formulario
  const submitHandler = data => {
    console.log(data);
    if (!paymentMethod) {
      console.log(data);
    } else {
      console.log('ahora no');
      // dispatch({ type: 'SAVE_PAYMENT_METHOD', payload: paymentMethod });
      // Cookies.set('paymentMethod', paymentMethod);
      // router.push('/placeorder');
    }
  };

  return (
    <Layout title='Payment Method'>
      <Main css='padding--32'>
        <form
          onSubmit={handleSubmit(submitHandler)}
          className='display--grid gap--8'
        >
          <HeadlineThree>Payment Methods</HeadlineThree>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='PayPal'
            render={({ field }) => (
              <label>
                <input name='paymentMethod' type='radio' {...field} />
                <span>PayPal</span>
              </label>
            )}
          ></Controller>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='Stripeaaa'
            render={({ field }) => (
              <label>
                <input
                  defaultChecked='true'
                  name='paymentMethod'
                  type='radio'
                  {...field}
                />
                <span>Stripe</span>
              </label>
            )}
          ></Controller>
          <Controller
            name='paymentMethod'
            control={control}
            defaultValue='Cash'
            render={({ field }) => (
              <label>
                <input
                  name='paymentMethod'
                  type='radio'
                  value='Cash'
                  {...field}
                />
                <span>Cash</span>
              </label>
            )}
          ></Controller>
          <Section>
            <Button type='submit' kind='action'>
              Continue
            </Button>{' '}
            <Button onClick={() => router.push('/shipping')}>Back</Button>
          </Section>
        </form>
      </Main>
    </Layout>
  );
}

When I execute this, only receive an: Object {paymentMethod: "PayPal"} and I suspect it is because it's the first on the group.当我执行此操作时,只收到一个:Object {paymentMethod: "PayPal"} 我怀疑这是因为它是该组中的第一个。 Maybe I am missing something in order to get the selected value, not the first one one of the group.也许我为了获得所选值而遗漏了一些东西,而不是该组中的第一个。

You juste have to do the following to register input type radio.您只需执行以下操作即可注册输入类型收音机。 Controller ins't needed in your case: Controller 在您的情况下不需要:

const Component = () => {
  const { register, handleSubmit } = useForm();

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <input type="radio" {...register('paymentMethod')} value="PayPal" />
      <input type="radio" {...register('paymentMethod')} value="Stripeaaa" />
      <input type="radio" {...register('paymentMethod')} value="Cash" />

      <button>Submit</button>
    </form>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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