Select 反应中的文本-select

Select text in react-select

我能够以编程方式聚焦 react-select,但我不能 select 输入字段中的文本。

我正在获取对 react-select 的引用,如下所示:

const selectRef = useRef()
...
<Select
  ref={selectRef}
  // other props
</Select>

然后:

selectRef.current.focus()
selectRef.current.select()

Select 成功聚焦,但对于第二行(我相信 should work on an input element)我得到:

TypeError: selectRef.current.select is not a function

如何 select 在 react-selectinput 字段中输入文本?

只是一些变化 -:

<Select
  ref={(n) => this.selectRef = n}
  // other props
</Select>

我们可以像这样访问 inputValue --> this.selectRef.select.props.inputValue

工作 Fiddle -> https://stackblitz.com/edit/react-43utra

react-select,我相信,以编程方式处理这个焦点。 ref.current 不是搜索输入。

但是,我们可以使用相同的 HTMLInputElement's select() 方法实现预期的行为。 react-select 提供了一个属性 inputId,其值作为 Id 直接附加到输入。 onFocus 我们可以 select 它。

import React, {Component} from "react";
import Select from "react-select";

function SingleSelect() {
  const selectRef = useRef(null);

  function handleButtonClick() {
    selectRef.current.focus();
  }

  function handleFocus() {
    document.querySelector("#select-input").select();
  };

  return (
    <>
      <Select 
        inputId = "select-input"
        ref={selectRef}
        onFocus = {handleFocus}
        options = {[
          {value: "1", label: "one"},
          {value: "2", label: "two"},
        ]}
        defaultInputValue = "some random string"
      />
      <button onClick={handleButtonClick}>Focus!</button>
    </>
  );
}

这是相同代码的working example。 我希望这就是你想要的。谢谢:)

您的代码不起作用的原因是 Select 组件的引用与输入的 innerRef 不同。您可以通过以下对象链访问它...

selectRef -> 当前 (StateManager) -> select(Select 组件) -> inputRef (输入组件)

selectRef.current.select.inputRef.select()