javascript - 使用 Material UI react 自动完成

标签 javascript reactjs typescript autocomplete material-ui

我正在使用 Material UI 库实现一个组件自动完成功能。
但是有一个问题 - 我不确定如何正确传递 value 和 onChange,因为我有一个 TextField 的自定义实现,它也需要 value 和 onChange。我应该将 value 和 onChange 两次传递给 Autocomplete 和 TextField 吗?或者也许有更好的解决方案?将不胜感激任何帮助!
这是我的代码:

import { Autocomplete as MuiAutocomplete } from '@material-ui/lab'
import { FormControl } from 'components/_helpers/FormControl'
import { useStyles } from 'components/Select/styles'
import { Props as TextFieldProps, TextField } from 'components/TextField'

export type Props = Omit<TextFieldProps, 'children'> & {
  options: Array<any>
  value: string
  onChange: (value: string) => void

  disabled?: boolean
}

export const Autocomplete = (props: Props) => {
  const classes = useStyles()

  return (
    <FormControl
      label={props.label}
      error={props.error}
      helperText={props.helperText}
    >
      <MuiAutocomplete
        options={props.options}
        // value={props.value}
        // onChange={event =>
        //   props.onChange((event.target as HTMLInputElement).value as string)
        // }
        classes={{
          option: classes.menuItem,
        }}
        disabled={props.disabled}
        getOptionLabel={option => option.label}
        renderInput={params => (
          <TextField
            {...params}
            placeholder={props.placeholder}
            value={props.value}
            onChange={props.onChange}
          />
        )}
        renderOption={option => {
          return <Typography>{option.label}</Typography>
        }}
      />
    </FormControl>
  )
}```

最佳答案

Material UI 具有内置的 Prop 来处理自动完成与输入值的状态。
您可以在此处的文档中看到它的使用情况:https://material-ui.com/components/autocomplete/#controllable-states
在您的示例中,您需要添加 inputChangeonInputChange自动完成组件的 Prop 。这些将通过传递给 renderInput 的参数传递给您的 TextField功能。
因此,您的最终代码将类似于从链接文档复制的以下代码段:

<Autocomplete
  value={value}
  onChange={(event, newValue) => {
    setValue(newValue);
  }}
  inputValue={inputValue}
  onInputChange={(event, newInputValue) => {
    setInputValue(newInputValue);
  }}
  id="controllable-states-demo"
  options={options}
  style={{ width: 300 }}
  renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
/>

关于javascript - 使用 Material UI react 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68086839/

相关文章:

javascript - 使用 Google Apps 脚本设置 Sendinblue 邮件服务

javascript - 在单独的框架中执行 Javascript

javascript - 检查 React 中的状态是脏的还是干净的

forms - 如何在semantic-ui-react中禁用表单自动完成?

typescript - 如何将nestjs应用程序部署到Dreamhost VPS

带有 ControlValueAccessor 和 formControlName 的 Angular Material Datepicker

javascript - 将附加的 html 附加到 jquery 中的克隆对象

javascript - Image caption - 我不想让它消失

javascript - 模块构建失败 : ReferenceError: window is not defined

javascript - typescript 函数参数