20211115 - A component is changing an uncontrolled Autocomplete to be controlled
2021-11-15 00:00:00
# Solved
# Material UI

autocomplete 有两个独立的值,value 和 inputValue,各自都需要state来更新
而且注意这里 autocomplete 的value的一个object,所以value的state初始值也应该是一个object。否则inputValue 会变成 undefined

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import React from 'react' import TextField from '@material-ui/core/TextField' import Autocomplete from '@material-ui/lab/Autocomplete'
const options = ['Option 1', 'Option 2']
export default function AutocompleteLab() { const [value, setValue] = React.**useState(options[0])** const [inputValue, setInputValue] = React.useState('')
return ( <div> <div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div> <div>{`inputValue: '${inputValue}'`}</div> <br /> <Autocomplete value={value} onChange={(_, newValue) => { setValue(newValue) }} inputValue={inputValue} onInputChange={(_, newInputValue) => { setInputValue(newInputValue) }} options={options} style={{ width: 300 }} renderInput={(params) => <TextField {...params} label="Name" variant="outlined" />} /> </div> ) }
|
A component is changing an uncontrolled Autocomplete to be controlled