簡體   English   中英

使用 Material UI 響應自動完成

[英]React Autocomplete with Material UI

我正在使用 Material UI 庫實現一個組件自動完成。

但是有一個問題 - 我不確定如何正確傳遞 value 和 onChange,因為我有一個 TextField 的自定義實現,它也需要 value 和 onChange。 我應該將 value 和 onChange 傳遞兩次 - 自動完成和 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 內置了道具來處理自動完成與輸入值的狀態。

您可以在此處的文檔中看到它的使用情況: https : //material-ui.com/components/autocomplete/#controllable-states

在您的示例中,您可能希望將inputChangeonInputChange道具添加到 Autocomplete 組件。 這些將通過傳遞給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" />}
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM