为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

杨__羊羊 2022-09-29 15:44:31
我正在使用 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]名字”啊哈
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

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


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

  )

}

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


查看完整回答
反对 回复 2022-09-29
?
慕哥9229398

TA贡献1877条经验 获得超6个赞

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


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`}

/>


查看完整回答
反对 回复 2022-09-29
  • 2 回答
  • 0 关注
  • 88 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号