簡體   English   中英

將“標簽”道具傳遞給 Formik<field /> 與 Material UI 一起使用時<textfield />

[英]Passing a 'label' prop into Formik <Field /> when using alongside Material UI <TextField />

我正在使用 Formik 和 Material UI 構建一個表單。

我通過以下方式利用 Formik 組件:

我的輸入組件:

const Input = ({ field, form: { errors } }) => {
  const errorMessage = getIn(errors, field.name);
  return <TextField {...field} />;
};

進入我的渲染形式,我是這樣做的:

<Field
  component={Input}
  name={`patients[${index}].firstName`}
/>

問題是 Material UI 使用 label 道具在輸入字段上顯示 label 因此 label 應該是傳遞給的道具。 如果我將它“硬編碼”到我的“輸入”組件中,它就可以工作,這違背了使用可重用組合的目的。

所以這可行但不方便:

const Input = ({ field, form: { errors } }) => {
  console.log(field.label);
  const errorMessage = getIn(errors, field.name);
  return <TextField {...field} label="first name" />;
};

我希望的是使用它上一級,例如:

<Field
  component={Input}
  name={`patients[${index}].firstName`}
  label="first name"
/>

但是以上內容不起作用,因為 Formik 不將“標簽”識別為道具(或者這就是我的理解,但我可能錯了)。

有沒有人遇到過這個問題?

我知道我可以將我的“姓名”值用作 label,但這不是很好的用戶體驗,因為它會給我留下 label,例如“患者 [0].firstName”啊哈

這是一個很好的解決方案,本質上是您的,但您可以提供任何東西,而不僅僅是 label。 創建字段並將 label 放在類似這樣的位置:

<Field name={`patients[${index}].firstName`} label='First Name' component={MuiTextFieldFormik} />

訣竅是使用擴展運算符,然后自定義組件變為:

import React from 'react';
import { TextField } from "@material-ui/core"
import { get } from "lodash"

export const MuiTextFieldFormik = ({ field, form: { touched, errors }, ...props }) => {
  const error = get(touched, field.name) && !!get(errors, field.name)
  const helperText = get(touched, field.name) && get(errors, field.name)

  return (
    <TextField fullWidth variant="outlined" {...field} {...props} error={error} helperText={helperText} />
  )
}

令人失望的是他們的文檔沒有這么簡單的例子

好的,所以我想我找到了解決方案。 我破壞 arguments 的方式,我只傳遞了保存大部分數據的字段和表單,因此通過 label 道具以這種方式修復:

const Input = ({ field, label, form: { errors } }) => {
  const errorMessage = getIn(errors, field.name);
  return <TextField {...field} label={label} />;
};

然后,當我以這種方式使用 Formik 組件時,正確的 label 會通過:

<Field
  label="first name"
  component={Input}
  name={`patients[${index}].firstName`}
/>

暫無
暫無

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

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