问题
I have a material-ui autocomplete element
<Autocomplete
id="combo-box-demo"
autoHighlight
openOnFocus
autoComplete
options={this.state.products}
getOptionLabel={option => option.productName}
style={{ width: 300 }}
onChange={this.selectProduct}
renderInput={params => (
<TextField {...params} label="Select Product Name" variant="outlined" />
)}
/>;
I want this element to get focus when I click a button.
I tried using references as discribed here how react programmatically focus input
It worked for other elements but not for autocomplete
please help
回答1:
You should save a reference to the TextField
component, and use this ref to focus once another element is clicked (once some event was triggered).
let inputRef;
<Autocomplete
...
renderInput={params => (
<TextField
inputRef={input => {
inputRef = input;
}}
/>
)}
/>
<button
onClick={() => {
inputRef.focus();
}}
Here is a link to a working example: https://codesandbox.io/s/young-shadow-8typb
You can play with the
openOnFocus
property of the Autocomplete to decide if you just want focus on the input or you want the dropdown of the autocomplete to open.
来源:https://stackoverflow.com/questions/61079240/react-material-ui-autocomplete-element-focus-onclick