簡體   English   中英

如何獲取 Formik 表單上按下按鈕的值?

[英]How do I get the value of the pressed button on a Formik form?

在 React 應用程序中使用 Formik 時,具有多個按鈕的表單定義如下:

<button type="submit" name="action" value="unlock">Unlock account</button>
<button type="submit" name="action" value="delete">Delete account</button>

如何獲取按下按鈕的name和/或value

我確實嘗試將字段action添加到我的initialValues ,但它仍然是空白的。

我找到了一種解決方法,即以這種方式定義我的按鈕:

<button type="submit" onClick={() => setFieldValue("action", "unlock")}>unlock</button>
<button type="submit" onClick={() => setFieldValue("action", "delete")}>delete</button>

然后在 Formik 的onSubmit回調中,我檢查並重置action字段。

這是一種將onSubmit包裝在表單中並使用event.submitter屬性獲取對按下的按鈕的引用的方法,然后在最終處理表單之前將其設置到 Formik 中。

<Formik
  initialValues={{}}
  onSubmit={async values => {
    console.log('onSubmit', values);
  }}
>
  {({ handleSubmit, setFieldValue }) => (
    <form
      onSubmit={jsEvent => {
        // This is a bit of a hack to copy the name and value of
        // the submitter into the Formik form
        const { name, value } = jsEvent.nativeEvent.submitter;
        setFieldValue(name, value);

        return handleSubmit(jsEvent);
      }}
    >
      ...
    </form>
  )}
</Formik>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM