react material ui autocomplete element focus onclick

情到浓时终转凉″ 提交于 2021-02-07 13:43:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!