gpt4 book ai didi

reactjs - 在 react 选择中选择文本

转载 作者:行者123 更新时间:2023-12-02 02:53:26 24 4
gpt4 key购买 nike

我能够以编程方式聚焦 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-selectinput 字段中选择文本?

最佳答案

我相信

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

我们可以使用相同的 HTMLInputElement's select() 来实现预期的行为然而方法。react-select 提供了一个 prop 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相同的代码。我希望这就是你想要的。谢谢:)

关于reactjs - 在 react 选择中选择文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61577348/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com