简体   繁体   中英

When i change the select i receive: 'Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>'

I have this material select component:

<FormControl fullWidth variant="outlined" className={classes.formControl}>
  <InputLabel ref={inputLabel} htmlFor="outlined-age-native-simple">
    Filial
  </InputLabel>
  <Select
    onChange={handleChange}
    onBlur={handleBlur}
    error={touched.filial && Boolean(errors.filial)}
    value={values.filial}
    defaultValue={'DEFAULT'}
    inputProps={{
      name: 'filial',
      id: 'outlined-filial-native-simple',
    }}
  >
    <option value="DEFAULT" disabled>Choose a salutation ...</option>
    <option value={10}>Ten</option>
    <option value={20}>Twenty</option>
    <option value={30}>Thirty</option>
  </Select>
</FormControl>

When i change the option selected i receive:

index.js:1 Warning: Use the defaultValue or value props on instead of setting selected on

I'm using formik to treat my form:

const enhanceWithFormik = withFormik({
  mapPropsToValues: () => ({ email: '', password: '', filial: '' }),
  handleSubmit: values => {
    console.log(values)
  },
  isInitialValid: false,
  validateOnChange: true,
  validateOnBlur: true,
  displayName: 'MyForm',
  validationSchema: schema
})

When i fill the fields of my form and click in the submit button is printing corretly the value of filial that i select in the form, but is throwing this error in my console.

How i can fix this?

I encountered the same thing and now I resolved it. I'm not using formik in my project, but the following is similar to my approach and hope it helps.

First, in your <Select> tag you have both value and defaultValue . But just having one of them is fine. (notice the warning you received says "Use the defaultValue or value props"). In your case, let's say you would remove the defaultValue and keep the value .

Now, make sure values.filial is set as 'DEFAULT' , so value={values.filial} would mean the initial value is 'DEFAULT' , and the drop down will initially display Choose a salutation ...

The handleChange function should then re-render the component as the drop down selection is changed.

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