我能够以编程方式聚焦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的input字段中的文本?
发布于 2020-05-18 01:43:36
我相信,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。我希望这是你想要的。谢谢:)
发布于 2020-05-30 02:05:33
您的代码不能工作的原因是,对Select组件的引用与对输入的innerRef不同。你可以通过下面的对象链来访问它。
selectRef -> current (StateManager) -> Select(选择组件) -> inputRef (输入组件)
selectRef.current.select.inputRef.select()发布于 2020-05-04 00:07:48
只有几个变化-:
<Select
ref={(n) => this.selectRef = n}
// other props
</Select>我们可以像这样访问inputValue --> this.selectRef.select.props.inputValue
Working Fiddle -> https://stackblitz.com/edit/react-43utra
https://stackoverflow.com/questions/61577348
复制相似问题