fluent UI 中的Combobox如何在option的上面加一个input

fluent UI 9 中的Combobox如何在它自带的input框下面,option的上面,再加一个用于search的input框

会出现一个问题,点击search input框,可以触发input的onClick事件,但是无法获取焦点,焦点还在select的下拉框中

这种情况是由于 Combobox 的默认行为或者事件冒泡导致的。

解决方法:

bash 复制代码
const inputRef = React.useRef<any>(null);
 <Combobox
        aria-labelledby={comboId}
        placeholder="Select an animal"
        open={isOpen}
        onOpenChange={(event, data) => {
          setIsOpen(data.open);
          console.log(data.open, isOpen, 'setIsOpen');
        }}
        {...props}
        onClick={() => setIsOpen(true)} // 点击 Combobox 保持下拉框打开
      >
        <Input
          contentBefore={<SearchRegular />}
          ref={inputRef}
          onClick={(ev) => {
            ev.stopPropagation();
            inputRef.current?.focus();
            setIsOpen(true); // 点击 Input 保持下拉框打开
            console.log(ev, 'Input clicked');
          }}
        />
        {options.map((option) => (
          <Option key={option} disabled={option === 'Ferret'}>
            {option}
          </Option>
        ))}
      </Combobox>

首先在input的唯一可以触发的onClick方法中取消默认冒泡行为,(此时onFocus,onChange事件都不会触发)

然后强制设置焦点,在 onClick 事件中,手动将焦点设置到 Input 元素上,通过ref,走到这一步会发现点击input之后,下拉框消失了,这时候就要用到Combobox的open属性,点击input后,设置open的值一直是打开状态。使用onOpenChange,监听当点击其他地方时的监听事件。

这样就可以输入了,其他操作也会很流畅。

可以在官网链接测试
https://stackblitz.com/edit/9jdz2a-yxlsnb?file=src%2Fexample.tsx

完整代码

bash 复制代码
import * as React from 'react';
import {
  Combobox,
  makeStyles,
  Option,
  useId,
  Input,
} from '@fluentui/react-components';
import { SearchRegular } from '@fluentui/react-icons';
import type { ComboboxProps } from '@fluentui/react-components';

const useStyles = makeStyles({
  root: {
    // Stack the label above the field with a gap
    display: 'grid',
    gridTemplateRows: 'repeat(1fr)',
    justifyItems: 'start',
    gap: '2px',
    maxWidth: '400px',
  },
});

export const Default = (props: Partial<ComboboxProps>) => {
  const comboId = useId('combo-default');
  const [isOpen, setIsOpen] = React.useState(false);
  const options = ['Cat', 'Dog', 'Ferret', 'Fish', 'Hamster', 'Snake'];
  const styles = useStyles();
  const inputRef = React.useRef<any>(null);

  return (
    <div className={styles.root}>
      <label id={comboId}>Best pet</label>
      <Combobox
        aria-labelledby={comboId}
        placeholder="Select an animal"
        open={isOpen}
        onOpenChange={(event, data) => {
          setIsOpen(data.open);
          console.log(data.open, isOpen, 'setIsOpen');
        }}
        {...props}
        onClick={() => setIsOpen(true)} // 点击 Combobox 保持下拉框打开
      >
        <Input
          contentBefore={<SearchRegular />}
          ref={inputRef}
          onClick={(ev) => {
            ev.stopPropagation();
            inputRef.current?.focus();
            setIsOpen(true); // 点击 Input 保持下拉框打开
            console.log(ev, 'Input clicked');
          }}
        />
        {options.map((option) => (
          <Option key={option} disabled={option === 'Ferret'}>
            {option}
          </Option>
        ))}
      </Combobox>
    </div>
  );
};
相关推荐
华洛15 小时前
多写点skill吧,写的越多这行业死的越快。
前端·javascript·产品
swipe20 小时前
纯函数、柯里化与函数组合:从原理到源码,构建更可维护的前端代码体系
前端·javascript·面试
Lee川21 小时前
JavaScript 中的 `this` 与变量查找:一场关于“身份”与“作用域”的深度博弈
前端·javascript·面试
Kakarotto1 天前
Canvas 直线点击事件处理优化
javascript·vue.js·canvas
进击的尘埃1 天前
Playwright Component Testing 拆到底:组件怎么挂上去的,快照怎么在 CI 里不翻车
javascript
左夕1 天前
最基础的类型检测工具——typeof, instanceof
前端·javascript
yuki_uix1 天前
递归:别再"展开脑补"了,学会"信任"才是关键
前端·javascript
用户5757303346241 天前
🐱 从“猫厂”倒闭到“鸭子”横行:一篇让你笑出腹肌的 JS 面向对象指南
javascript
码路飞1 天前
GPT-5.4 Computer Use 实战:3 步让 AI 操控浏览器帮你干活 🖥️
java·javascript
进击的尘埃1 天前
Service Worker 离线缓存这事,没你想的那么简单
javascript