在与 Material UI <TextField /> 一起使用时将 'label' 道具传递给 Formik <Field />

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 属性在输入字段上显示标签,因此标签应该是传递给 的属性。 如果我 "hard-code" 它进入我的 "Input" 组件,它会工作,这违背了使用可重用组件的目的。

这样可行但不方便:

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"
/>

但是上面的方法不起作用,因为 "label" 没有被 Formik 识别为道具(或者我是这么理解的,但我可能是错的)。

有人遇到过这个问题吗?

我知道我可以使用我的 "name" 值作为标签,但它不是很好的用户体验,因为它会给我留下诸如 "patients[0].firstName" 啊哈

之类的标签

好的,我想我找到了解决方案。我破坏我的论点的方式,我只传递了字段和表单,它们保存了大部分数据,因此以这种方式传递标签道具修复了:

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

然后当我以这种方式使用 Formik 组件时,正确的标签得到传递:

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

这是一个很好的解决方案,基本上是你的,但你可以提供任何东西,而不仅仅是标签。 创建字段并像这样放置标签:

<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} />
  )
}

令人失望的是他们的文档没有这么简单的例子