将“标签”道具传递到 Formik <字段 />与材料 UI 一起使用时<文本字段 />

我正在使用 Formik 和材质 UI 构建一个窗体。


我通过以下方式利用 Formik 组件:


我的输入组件 :


const Input = ({ field, form: { errors } }) => {

  const errorMessage = getIn(errors, field.name);

  return <TextField {...field} />;

};

向下到我的渲染形式,这是我是如何做到的:


<Field

  component={Input}

  name={`patients[${index}].firstName`}

/>

问题在于材质 UI 使用标签属性在输入字段上显示标签,因此标签应该是传递给 的 prop。如果我将它“硬编码”到我的“输入”组件中,它就会起作用,这违背了使用可重用合成的目的。


所以这有效但不方便:


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]名字”啊哈


杨__羊羊
浏览 89回答 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 }) => {&nbsp; const error = get(touched, field.name) && !!get(errors, field.name)&nbsp; const helperText = get(touched, field.name) && get(errors, field.name)&nbsp; return (&nbsp; &nbsp; <TextField fullWidth variant="outlined" {...field} {...props} error={error} helperText={helperText} />&nbsp; )}令人失望的是,他们的文档没有这么简单的例子

慕哥9229398

好吧,所以我想我找到了解决方案。我破坏参数的方式是,我只是传递字段和表单,这些字段和表单保存了大部分数据,因此以这种方式传递标签道具可以修复:const Input = ({ field, label, form: { errors } }) => {&nbsp; const errorMessage = getIn(errors, field.name);&nbsp; return <TextField {...field} label={label} />;};然后,当我以这种方式使用 Formik 组件时,正确的标签被传递:<Field&nbsp; label="first name"&nbsp; component={Input}&nbsp; name={`patients[${index}].firstName`}/>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript