【问题标题】:React Autocomplete with Material UI使用 Material UI 反应自动完成
【发布时间】:2021-09-06 05:48:07
【问题描述】:

我正在使用 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>
  )
}```

【问题讨论】:

    标签: javascript reactjs typescript autocomplete material-ui


    【解决方案1】:

    Material UI 具有内置的道具来处理自动完成与输入值的状态。

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

    在您的示例中,您可能希望将 inputChangeonInputChange 属性添加到自动完成组件。这些将通过传递给 renderInput 函数的参数传递给您的 TextField。

    因此,您的最终代码将类似于以下从链接文档复制的 sn-p:

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

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2020-12-14
      • 2020-07-30
      • 1970-01-01
      • 2022-01-04
      • 2021-10-04
      • 2020-09-18
      • 2020-05-04
      • 2020-03-12
      相关资源
      最近更新 更多