【发布时间】: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