如何在其父组件挂载时让语义 UI React Dropdown 自动聚焦?

spi*_*rit 3 autofocus dropdown semantic-ui-react

我正在使用Semantic React UI 的 Dropdown,我希望它在其父组件安装后立即获得焦点:用户应该能够立即搜索。

我尝试使用render()父级的引用:

<Dropdown ref={dd => (this.MyDropdown = dd)}
        ... />
Run Code Online (Sandbox Code Playgroud)

...然后componentDidMount在父组件的函数中调用它的焦点。但是Dropdown没有功能focus,所以这个方法行不通。

componentDidMount() {
    // I want to do something like the next line here, but 'focus' is not available on the component.
    //this.MyDropdown.focus();
  }
Run Code Online (Sandbox Code Playgroud)

那我应该怎么做呢?

这是我迄今为止在 codeandbox 上尝试过的。请注意 中注释掉的行componentDidMount

董承樺*_*董承樺 7

尝试这个:

<Dropdown searchInput={{ autoFocus: true }} />
Run Code Online (Sandbox Code Playgroud)

修改后,您的代码将如下所示

<Dropdown
    ref={dd => (this.MyDropdown = dd)}
    placeholder="Please type something, dude"
    fluid
    search
    selection
    options={options}
    searchInput={{ autoFocus: true }}
  />
Run Code Online (Sandbox Code Playgroud)

参考: