目前正在尝试将 Material UI 的 Autocomplete 组件与 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]
}
],