首頁  >  問答  >  主體

在react-hook-form狀態下儲存按鈕組中的選取值

我嘗試將 MUI 按鈕群組中的選定值儲存到react-hook-form 的狀態,但遇到一些問題 - 該值未正確更新。

codesandbox 連結在這裡

這是我的程式碼的通用版本:

import { ButtonGroup, Button } from '@mui/material'
import { useForm, Controller } from 'react-hook-form'

export default function MyComponent() {
  const { control, setValue, getValues } = useForm()

  const options = ['Option1', 'Option2', 'Option3']

  return (
    <Controller
      name="selectedOption"
      control={control}
      render={({ field }) => (
        <ButtonGroup>
          {options.map((option) => {
            return (
              <Button
                key={option}
                variant={field.value === option ? 'contained' : 'outlined'}
                onClick={() => {
                  setValue('selectedOption', option)  {/* this trick didn't work */}
                }}
              >
                {option}
              </Button>
            )
          })}
        </ButtonGroup>
      )}
    />
  )
}

我使用了setValue('selectedOption', option),但不確定這是否是一個很好的做法。

我面臨的問題是,當我單擊按鈕群組中的按鈕時,我希望表單狀態中的 selectedOption 值更新為單擊按鈕的值。但是,getValues 方法似乎沒有反映更新後的狀態。

這裡可能出現什麼問題?當單擊按鈕組中的按鈕時,如何成功更新和檢索 selectedOption 值?

預先感謝您的幫忙!

P粉106715703P粉106715703379 天前483

全部回覆(1)我來回復

  • P粉465287592

    P粉4652875922023-09-09 09:17:43

    您將需要使用FormProvideruseFormContext 如果您#將上下文作為道具傳遞給您的Form元件。 (我認為您希望透過查看範例來做到這一點)。

    來自 useFormContext 文件

    例如:

    export default function MyComponent() {
      const methods = useForm();
    
      return (
        {/* Add FormProvider with useForm return props */}
        <FormProvider {...methods}>
    
          ...
    
        </FormProvider>
      );
    }
    
    const Form = () => {
      // Retrieve your setter/getter functions from useFormContext
      const { control, setValue, getValues } = useFormContext();
      const options = ["Option1", "Option2", "Option3"];
    
      ...
    };

    工作CodeSandbox: https://codesandbox.io/s/react-hook-form-no-props-kngps3?file=/src/Form.jsx

    回覆
    0
  • 取消回覆