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

j0pj023g  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(92)

如何在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!"
/>
jei2mxaa

jei2mxaa1#

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!"
/>

相关问题