簡體   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