首页 > 解决方案 > Material-UI 自动完成组件未将值传播到 TextField 组件

问题描述

我将 Formik 与 Yup 和 Material-UI 一起使用。我有一个包含 Material-UI 自动完成组件的表单我想在提交表单时从自动完成组件中检索用户设置的值。

目前,使用 Autocomplete 组件设置的值似乎没有传播到底层 TextField 组件。当使用自动完成选择一个值并提交表单时,表单上的处理字段上的值为空。

父 (App.js) 组件:

const INITIAL_FORM_STATE = {
  treatment: '',
};

const FORM_VALIDATION = Yup.object().shape({
  treatment: Yup.string().required('Required'),
});

...

<Formik
  initialValues={{ ...INITIAL_FORM_STATE }}
  validationSchema={FORM_VALIDATION}
  onSubmit={(values) => {
    console.log(values);
  }}
>
  <Form>
    <Treatments name='treatment' />
    <Buttontype='submit'>Search</Button>
  </Form>
</Formik>

治疗组件:

import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import { InputAdornment } from '@material-ui/core';
import SearchIcon from '@material-ui/icons/Search';
import { useField } from 'formik';

const Treatments = ({ name, ...otherProps }) => {
  const [field, meta] = useField(name);

  const configTextfield = {
    ...field,
    ...otherProps,
    fullWidth: true,
    variant: 'outlined',
  };

  if (meta && meta.touched && meta.error) {
    configTextfield.error = true;
    configTextfield.helperText = meta.error;
  }

  return (
    <Autocomplete
      id='treatments'
      disableClearable
      options={treatments.map((treatment) => treatment.title)}
      renderInput={(params) => (
        <TextField
          {...configTextfield}
          {...params}
          label='Search for treatments'
          margin='normal'
          InputProps={{
            ...params.InputProps,
            autoComplete: 'disabled',
            type: 'search',
            startAdornment: (
              <InputAdornment position='start'>
                <SearchIcon />
              </InputAdornment>
            ),
          }}
        />
      )}
    />
  );
};

const treatments = [
  { id: 't01', title: 'Foo' },
  { id: 't02', title: 'Bar' },
];

export default Treatments;

我尝试将 a 添加valueRef到 Treatments 组件并使用onInputChangeAutocomplete 组件上的 prop 设置它,然后将该值分配给inputRefTextField 组件。但这什么也没做,也没有返回错误。

标签: reactjsmaterial-uiformikyupformik-material-ui

解决方案


推荐阅读