简体   繁体   English

如何在 Material UI 中设置日期文本字段的值

[英]How to set value of a Date Textfield in Material UI

I've got an array of objects, where each object contains an id and a date value.我有一个对象数组,其中每个对象都包含一个 id 和一个日期值。 For example, my array, call it stepDates , could look something like this:例如,我的数组,称为stepDates ,可能如下所示:

[
  {
    id: 1,
    date: "2021-07-23"
  },
  {
    id: 2,
    date: null
  },
  {
    id: 3,
    date: null
  }
]

I also have another array of objects, where there is more information on the objects that you see above.我还有另一个对象数组,其中包含有关您在上面看到的对象的更多信息。 This array looks something like:这个数组看起来像:

const steps = [
  {
    id: 1,
    name: start
  },
  {
    id: 2,
    name: middle
  },
  {
    id: 3,
    name: end
  }
]

I'm trying to iterate over each of the objects in the above array to display the date using TextField with Material UI (without the user having to select the date themselves).我正在尝试遍历上述数组中的每个对象,以使用带有 Material UI 的TextField显示日期(用户不必自己选择日期)。 However, I am getting an error when setting the value prop for the TextField component.但是,在为TextField组件设置value属性时出现错误。 For now, I have this:现在,我有这个:

{steps.map((step, index) => {
  return (
    <TextField
      id={step.id}
      label={step.name}
      type={"date"}
      onChange={event => handleStepDateChange(event.target.value, step.name)}
      value={
        stepDates.map(stepDate => {
          if (stepDate.id === step.id) return stepDate.date
        })
      }
    />
  )
})}

Give the above, I am trying to either display the date from the stepDates for each object if it exists, otherwise, if it's null, I just want to display the date field unselected, such as "dd/mm/yyyy".给出上述内容,我试图显示每个对象的stepDates的日期(如果存在),否则,如果它为空,我只想显示未选中的日期字段,例如“dd/mm/yyyy”。

However, in doing the above, I am getting two different errors.但是,在执行上述操作时,我遇到了两个不同的错误。 The first error where the date field exists gives me the following:日期字段存在的第一个错误给了我以下信息:

The specified value "2021-07-23,,,,,,,,,,,,," does not conform to the required format, "yyyy-MM-dd"指定值“2021-07-23,,,,,,,,,,,,,,”不符合要求的格式,“yyyy-MM-dd”

And the second error where the date is null, gives me this error (twice for each date that is null as above):日期为空的第二个错误给了我这个错误(每个日期为空两次):

The specified value ",,,,,,,,,,,,," does not conform to the required format, "yyyy-MM-dd"指定值“,,,,,,,,,,,,,,”不符合要求格式,“yyyy-MM-dd”

you're going to want to use find instead of map .您将要使用find而不是map so you value attribute will look like so:所以你的 value 属性看起来像这样:

value={stepDates.find(stepDate => stepDate.id === step.id).date}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM