2

我正在使用 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 使用标签道具在输入字段上显示标签,因此标签应该是传递给 . 如果我将它“硬编码”到我的“输入”组件中,它就可以工作,这违背了使用可重用组合的目的。

所以这可行但不方便:

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 不将“标签”识别为道具(或者这就是我的理解,但我可能错了)。

有没有人遇到过这个问题?

我知道我可以使用我的“姓名”值作为标签,但这不是很好的用户体验,因为它会给我留下诸如“患者 [0].firstName”之类的标签啊哈

4

2 回答 2

2

这是一个很好的解决方案,本质上是您的,但您可以提供任何东西,而不仅仅是标签。创建字段并将标签放在类似的位置:

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

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

于 2020-12-23T00:20:23.713 回答
0

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

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`}
/>
于 2020-06-12T09:41:44.500 回答