在使用Headless UI组合框 Select 一个项目后,我正在try Select 底层输入控件中的所有文本.按照HeadlessUI以上的示例,我做了以下修改:

  1. 添加了对输入元素的引用,
  2. 从组合框的onChange()事件中 Select 输入元素中的文本.
import { Fragment, useState, useRef } from 'react'
import { Combobox, Transition } from '@headlessui/react'
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/20/solid'

const people = [
  { id: 1, name: 'Wade Cooper' },
  { id: 2, name: 'Arlene Mccoy' },
  { id: 3, name: 'Devon Webb' },
  { id: 4, name: 'Tom Cook' },
  { id: 5, name: 'Tanya Fox' },
  { id: 6, name: 'Hellen Schmidt' },
]

export default function Example() {
  const [selected, setSelected] = useState(people[0])
  const [query, setQuery] = useState('')

  const inputRef = useRef(null);

  const filteredPeople =
    query === ''
      ? people
      : people.filter((person) =>
          person.name
            .toLowerCase()
            .replace(/\s+/g, '')
            .includes(query.toLowerCase().replace(/\s+/g, ''))
        )

  return (
    <div className="fixed top-16 w-72">
      <Combobox value={selected} onChange={(value) => {
          setSelected(value);
          if (inputRef.current) {
            // Why isn't this selecting the text in the input? 
            inputRef.current.select();
          }
        }}>
        <div className="relative mt-1">
          <div className="relative w-full cursor-default overflow-hidden rounded-lg bg-white text-left shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-opacity-75 focus-visible:ring-offset-2 focus-visible:ring-offset-teal-300 sm:text-sm">
            <Combobox.Input
              className="w-full border-none py-2 pl-3 pr-10 text-sm leading-5 text-gray-900 focus:ring-0"
              displayValue={(person) => person.name}
              onChange={(event) => setQuery(event.target.value)}
              ref={inputRef}
            />
            <Combobox.Button className="absolute inset-y-0 right-0 flex items-center pr-2">
              <ChevronUpDownIcon
                className="h-5 w-5 text-gray-400"
                aria-hidden="true"
              />
            </Combobox.Button>
          </div>
          <Transition
            as={Fragment}
            leave="transition ease-in duration-100"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
            afterLeave={() => setQuery('')}
          >
            <Combobox.Options className="absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
              {filteredPeople.length === 0 && query !== '' ? (
                <div className="relative cursor-default select-none py-2 px-4 text-gray-700">
                  Nothing found.
                </div>
              ) : (
                filteredPeople.map((person) => (
                  <Combobox.Option
                    key={person.id}
                    className={({ active }) =>
                      `relative cursor-default select-none py-2 pl-10 pr-4 ${
                        active ? 'bg-teal-600 text-white' : 'text-gray-900'
                      }`
                    }
                    value={person}
                  >
                    {({ selected, active }) => (
                      <>
                        <span
                          className={`block truncate ${
                            selected ? 'font-medium' : 'font-normal'
                          }`}
                        >
                          {person.name}
                        </span>
                        {selected ? (
                          <span
                            className={`absolute inset-y-0 left-0 flex items-center pl-3 ${
                              active ? 'text-white' : 'text-teal-600'
                            }`}
                          >
                            <CheckIcon className="h-5 w-5" aria-hidden="true" />
                          </span>
                        ) : null}
                      </>
                    )}
                  </Combobox.Option>
                ))
              )}
            </Combobox.Options>
          </Transition>
        </div>
      </Combobox>
    </div>
  )
}

你有什么办法让这件事奏效吗?

推荐答案

try 在onChange处理程序中使用flushSync包装setter:

import { flushSync } from "react-dom";
.
.
.
<Combobox value={selected} onChange={(value) => {
  flushSync(() => {
    setSelected(value);
  })
  if (inputRef.current) {
     inputRef.current.focus();
     inputRef.current.select();
  }
}}>

参考文献:https://react.dev/learn/manipulating-the-dom-with-refs#flushing-state-updates-synchronously-with-flush-sync

Reactjs相关问答推荐

我想删除NextJs中的X轴标签APEXCHARTS

react 路由GUGUD Use Effect无法通过useNavigate正常工作

REACTION 18功能组件正在开发中的S

TanStack/Reaction-Query在我的Vercel应用程序中不起作用

如何使我的代码可以接受我想要的每一个链接

GitHub页面配置

我如何使用 React toastify (Promise) toast 和邮箱 js

如何将 MUI X 数据网格单元格方向更改为行级而不是列级?

Reactjs:MUI5:MobileDateTimePicker API:如何自定义日历中的文本

无法通过react 路由中的链接传递信息

这个简单的React组件为什么会多次渲染?

React - 将一个充满空值的无限大小的数组存储在 ref 中是否可以,或者我应该重置数组吗?

部署到github pages时请求路径错误

我正在通过 API(有效)从 MongoDB 传递数据.可视化但我不断收到此 TypeError: Cannot convert undefined or null to object

从一个获取 axios 请求(ReactJS)中删除默认参数

从 API 中提取映射数组后出现重复元素

Lodash 在命名导入中导入整个包

NextJs - 如何从站点 map 生成器中删除重复的 URL?

试图将页面限制为仅登录但有条件的用户似乎永远不会运行

如何在 React x 中返回组件?