繁体   English   中英

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

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

我正在学习在 React 和 Next.js 中编码,当涉及到在 forms 中提交数据时,使用 react-hook-forms 真的很容易,但是当涉及到单选按钮时,我有点挣扎。 我的应用程序中有一个步骤,我需要 select 3 之间的一个选项,我正在使用单选按钮来执行此操作。

我在这里使用的代码返回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>
  );
}

当我执行此操作时,只收到一个:Object {paymentMethod: "PayPal"} 我怀疑这是因为它是该组中的第一个。 也许我为了获得所选值而遗漏了一些东西,而不是该组中的第一个。

您只需执行以下操作即可注册输入类型收音机。 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