简体   繁体   中英

Typescript React <Select> onChange handler type error

I'm trying to add an onChange event handler to the Select component from material-ui:

<Select
      labelId="demo-simple-select-label"
      id="demo-simple-select"
      value={values.country}
      onChange={handleCountryChange}
    >
      {countries.map(c => {
        return (
          <MenuItem value={c}>{c}</MenuItem>
        )
      })}
    </Select>

and my event handler:

const handleCountryChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setValues({...values, country: event.target.value});
  };

but I get the following error:

Type '(event: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent<{ name?: string | undefined; value: unknown; }>, child: ReactNode) => void'.

What's wrong?

Since MUI Select in not a real select element you will need to cast e.target.value using as Type and type the handler as React.ChangeEvent<{ value: unknown }>

const handleCountryChange = (event: React.ChangeEvent<{ value: unknown }>) => {
  setValues({...values, country: event.target.value as string});
};

This is proper for the latest MUI 5 / Select

   const handleOnChange = (event: SelectChangeEvent<unknown>) => {
    const value = event.target.value as YourEnumType;
  };

对我来说似乎也违反直觉,但我必须这样做:

const handleChange = (e: ChangeEvent<{ value: string | unknown }>) => formik.setFieldValue('field', e.target.value)

I don't know where it's documented, but the Select module also exports SelectChangeEvent. This is what I used to get it:

import Select, {SelectChangeEvent} from '@mui/material/Select';

    const handleGenerationSelectChange = (event: SelectChangeEvent<string>, child: React.ReactNode) => {
    let genHolder = currentGeneration;
    genHolder.source = event.target.value as string;
    setCurrentGeneration({...genHolder});
};

It seems the definition for the change event is incorrect in the SelectInput.d.ts . More here: https://github.com/mui-org/material-ui/issues/15400#issuecomment-484891583

Try to use their recommended signature:

const handleCountryChange = (event: any) => { ... }

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