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

React中实现Autocomplete同时检索primaryText与secondaryText

Solution: Make Autocomplete Match Both Primary and Secondary Text

Got it, let's get your Autocomplete component searching both primaryText and secondaryText fields! The default Autocomplete.caseInsensitiveFilter likely only checks the primary text field, so we'll build a custom filter function that looks at both.

Step 1: Create a Custom Filter Function

First, define a filter that checks both text fields for a match (case-insensitive, just like the default):

const dualFieldFilter = (searchValue, item) => {
  // Normalize everything to lowercase to keep matching case-insensitive
  const normalizedSearch = searchValue.toLowerCase();
  const normalizedPrimary = item.primaryText.toLowerCase();
  const normalizedSecondary = item.secondaryText.toLowerCase();

  // Return true if either field contains the search term
  return normalizedPrimary.includes(normalizedSearch) || normalizedSecondary.includes(normalizedSearch);
};

Step 2: Update Your Autocomplete Component

Replace the default filter prop with our new custom function:

<Autocomplete 
  id={id} 
  placeholder={placeholder} 
  className="md-cell md-cell--4" 
  data={service_list} 
  filter={dualFieldFilter} // Use our custom dual-field filter here
  onAutocomplete={create_url_after_autocomplete} 
/>

How This Works

  • We convert both the search input and the text fields to lowercase to ensure case-insensitive matching (just like the default filter you were using).
  • The function checks if the search term exists in either primaryText or secondaryText — if either field has a match, the item is included in the autocomplete results.
  • Even if your secondaryText has truncated text (like "Police Verifi..." in your example), this still works because includes() checks for a substring match, regardless of trailing characters.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:15:20