You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用semantic-ui-react Dropdown的searchQuery属性且不破坏显示文本?

semantic-ui-react Dropdown设置searchQuery后选中项显示异常的解决方法

问题描述

使用semantic-ui-react的Dropdown组件时,设置searchQuery属性后,选中选项的显示文本无法正常展示,始终显示最近的搜索查询。即使根据选中值显式设置text属性,仍仅显示最近的查询内容。

复现代码如下(移除query、setQuery、searchQuery、onSearchChange和text可查看正常表现):

import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'

const countryOptions = [
  { key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
  { key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
  { key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]

const DropdownExampleSearchSelection = () => {
  const [value, setValue] = useState(null);
  const [query, setQuery] = useState('');
  const text = countryOptions.find(o => o.value === value)?.text;
  
  return (
    <div>
      <p>value: {value}</p>
      <p>text: {text}</p>
      <Dropdown
        placeholder='Select Country'
        fluid
        search
        selection
        options={countryOptions}
        searchQuery={query}
        onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
        value={value}
        onChange={(e, { value }) => setValue(value)}
        text={text}
      />
    </div>
  );
}

export default DropdownExampleSearchSelection

解决方法

核心问题是:当searchQuery存在值时,Dropdown会优先展示搜索查询内容,而非选中项的文本。因此需要在选中选项时清空searchQuery的状态,让Dropdown切换回显示选中项文本的模式。

修改后的代码如下:

import React, { useState } from 'react'
import { Dropdown } from 'semantic-ui-react'

const countryOptions = [
  { key: 'af', value: 'af', flag: 'af', text: 'Afghanistan' },
  { key: 'ax', value: 'ax', flag: 'ax', text: 'Aland Islands' },
  { key: 'al', value: 'al', flag: 'al', text: 'Albania' },
]

const DropdownExampleSearchSelection = () => {
  const [value, setValue] = useState(null);
  const [query, setQuery] = useState('');
  
  return (
    <div>
      <p>value: {value}</p>
      <Dropdown
        placeholder='Select Country'
        fluid
        search
        selection
        options={countryOptions}
        searchQuery={query}
        onSearchChange={(e, { searchQuery }) => setQuery(searchQuery)}
        value={value}
        onChange={(e, { value }) => {
          setValue(value);
          // 选中选项后清空搜索查询
          setQuery('');
        }}
      />
    </div>
  );
}

export default DropdownExampleSearchSelection

说明

  1. 移除了手动设置的text属性:Dropdown会自动根据value匹配对应选项的text,无需手动计算。
  2. 在onChange事件中添加setQuery(''):选中选项后立即清空搜索查询状态,Dropdown会自动切换为显示选中项的文本,不再保留之前的搜索词。

内容的提问来源于stack exchange,提问作者srk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 14:37:47