如何在React中使用formik实现自动完成,从对象数组中选择单个值和多个值?[在此处输入图像描述](https://i.stack.imgur.com/ekkAi.png)
arrayOfObject = [
{ id: 1, name: "test" },
{ id: 2, name: "test1" },
{ id: 3, name: "test2" },
]
< Autocomplete
id = "userId"
multiple
options = { arrayOfObject }
getOptionLabel = {(option) => option.name}
onChange = {(event, newValue) => {
const arrayOfIds = newValue.map((item) => item.id);
formik.setFieldValue('userId', arrayOfIds);
}}
value = {
ingredients.filter((option) =>
formik.values.userId.includes(option.id)
)
}
renderInput = {(params) => (
<TextField
{...params}
label="Ingredients"
variant="outlined"
inputProps={{
...params.inputProps,
'aria-label': 'Without label',
}}
/>
)}
renderTags = {(value, getTagProps) =>
value.map((option, index) => (
<Chip
key={index}
label={option.name}
{...getTagProps({ index })}
/>
))
}
noOptionsText = "Data not found!"
/>
1条答案
按热度按时间jei2mxaa1#