简体   繁体   中英

React Material UI select display value doesn't change when value is different from MenuItem text

I've got a Select that looks like this

<TextField
  id="year-select"
  select
  value={year ? year : "Select year"}
  onChange={(e) => setYear(e.target.value)}
>
<MenuItem value={moment().add(1, 'y')}>{moment().add(1, 'y').format('YYYY')}</MenuItem>
....
<MenuItem value={moment().add(10, 'y').format('YYYY')}>
{moment().add(10,'y').format('YYYY')}
</MenuItem>
</Textfield>

When the value is equal to menuitem's child value like the 2nd menuitem in the example the display value will change just fine, while if it's different it will be blank. I think this comes from the value prop in the select textfield, but changing it to having it like the 1st menuitem and then formatting the value in the prop doesn't work either.

Are there anyone that is aware of a solution I could use other than creating a handleChange handling two different variables for display and use?

You need to fill in the option for Select year. So either enter a placeholder (depending on your text field component) or add a menuitem like this: <MenuItem value={"Select year"}>{"Select year"}</MenuItem> To render the value for "Select year".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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