React Formik 自动完成从对象数组中选择值

问题描述 投票:0回答:1

如何在 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!"
/>
javascript reactjs material-ui autocomplete formik
1个回答
0
投票
  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!"
/>
© www.soinside.com 2019 - 2024. All rights reserved.