首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在react-select中选择文本

在react-select中选择文本
EN

Stack Overflow用户
提问于 2020-05-03 23:50:46
回答 3查看 2.4K关注 0票数 2

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

我得到了对react-select的引用,如下所示:

代码语言:javascript
复制
const selectRef = useRef()
...
<Select
  ref={selectRef}
  // other props
</Select>

然后:

代码语言:javascript
复制
selectRef.current.focus()
selectRef.current.select()

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

代码语言:javascript
复制
TypeError: selectRef.current.select is not a function

如何选择react-selectinput字段中的文本?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-05-18 01:43:36

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

然而,我们可以使用相同的HTMLInputElement's select()方法来实现预期的行为。react-select提供了一个适当的inputId,它的值作为Id直接附加到输入。onFocus我们可以选择它。

代码语言:javascript
复制
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。我希望这是你想要的。谢谢:)

票数 2
EN

Stack Overflow用户

发布于 2020-05-30 02:05:33

您的代码不能工作的原因是,对Select组件的引用与对输入的innerRef不同。你可以通过下面的对象链来访问它。

selectRef -> current (StateManager) -> Select(选择组件) -> inputRef (输入组件)

代码语言:javascript
复制
selectRef.current.select.inputRef.select()
票数 1
EN

Stack Overflow用户

发布于 2020-05-04 00:07:48

只有几个变化-:

代码语言:javascript
复制
<Select
  ref={(n) => this.selectRef = n}
  // other props
</Select>

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61577348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档