материал пользовательского интерфейса formik автозаполнение получить только значения в массиве полей - PullRequest
0 голосов
/ 09 мая 2020

В настоящее время пытается использовать компонент автозаполнения Material UI с Formik. Пока что такие вещи, как текстовые поля и традиционные выборки из Material-UI, очень хорошо работают с Formik. Реализация автозаполнения не так. моя проблема, когда я выбираю элемент из списка, я получил не только значение, но и объект, как его исправить, спасибо

const FAutocomplete = (props) => {
    const {
        field,
        form: { dirty, touched, errors, setFieldValue },
        options,
        getOptionLabel,
        textFieldProps,
        ...autoCompleteProps
    } = props

    // Merge default textFieldProps with textFieldProps passed in the component
    const mergedTextFieldProps = {
        ...FAutocomplete.defaultProps.textFieldProps,
        ...textFieldProps,
    }
    const errorText = getIn(errors, field.name)
    const touchedVal = getIn(touched, field.name)
    const hasError = dirty && touchedVal && errorText !== undefined
    const isMultiple = autoCompleteProps.multiple
    const isMultipleWithValue = isMultiple && field.value
    const canBeRendered = !isMultiple || isMultipleWithValue

    return (
        <>
            {canBeRendered && (
                <Autocomplete
                    options={options}
                    getOptionLabel={getOptionLabel}
                    onChange={(_, value) => setFieldValue(field.name, value)}
                    value={field.value}
                    getOptionSelected={(option, val) => option.value === val.value}
                    filterSelectedOptions 
                    renderInput={(params) => (
                        < TextField
                            {...params}
                            error={hasError}
                            helperText={hasError ? errorText : ''}
                            {...mergedTextFieldProps}
                        />
                    )}
                    {...autoCompleteProps}
                />
            )}
        </>
    )
}

FAutocomplete.propTypes = {
    form: PropTypes.shape({
        dirty: PropTypes.bool,
        errors: PropTypes.object,
        setFieldValue: PropTypes.func,
    }).isRequired,
    options: PropTypes.arrayOf(
        PropTypes.shape({
            label: PropTypes.string,
            value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        })
    ).isRequired,
    getOptionLabel: PropTypes.func,
    textFieldProps: PropTypes.shape({
        label: PropTypes.string,
        required: PropTypes.bool,
        fullWidth: PropTypes.bool,
        margin: PropTypes.oneOf(['none', 'dense', 'normal']),
    }),
}

FAutocomplete.defaultProps = {
    getOptionLabel: (option) => option.label,
    textFieldProps: {
        required: false,
        fullWidth: true,
        margin: 'normal',
    },
}

export default FAutocomplete


//How I use it;
<Field                                                                name={`types.${index}.typesof`}
options={data}
component={FAutocomplete}
size='small'
textFieldProps={{
label: 'types',
required: true,
variant: "standard",
placeholder: "types"
}}
multiple
/>


// initial values
const initialValues = {   
    types: []
}

const emptyTypesObject = {  
    typesof: [],
};


// where I do have problem is when choose from list my values  like below;
 "types": [
    {      
      "typesof": [
        {
          "label": "CSS",
          "value": "1"
        }
      ]
    }
  ],

// I want it to be like that only need to get the value of selected 
"types": [
    {      
      "typesof": [1]
    }
  ],
...