我可以通过编程使react-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
如何在react-select
的{{1}}字段中选择文本?
答案 0 :(得分:1)
您的代码不起作用的原因是因为对Select组件的引用与对输入的innerRef不同。您可以通过以下对象链来访问它...
selectRef->当前(StateManager)->选择(选择组件)-> inputRef(输入组件)
T
答案 1 :(得分:0)
只需几处更改-:
<Select
ref={(n) => this.selectRef = n}
// other props
</Select>
我们可以像这样访问inputValue
-> this.selectRef.select.props.inputValue
答案 2 :(得分:0)
react-select
以编程方式处理此焦点。 ref.current
不是搜索输入。
但是,我们可以使用相同的HTMLInputElement's select()方法来实现预期的行为。
react-select
提供了一个道具inputId
,其值直接作为ID附加到输入。 onFocus
我们可以选择它。
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,具有相同的代码。 希望这就是您想要的。谢谢:)