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
primaryTextorsecondaryText— if either field has a match, the item is included in the autocomplete results. - Even if your
secondaryTexthas truncated text (like "Police Verifi..." in your example), this still works becauseincludes()checks for a substring match, regardless of trailing characters.
内容的提问来源于stack exchange,提问作者Mayank Bansal
相关产品推荐
相关产品推荐

