Microsoft Graph Toolkit PeoplePicker组件搜索结果排序异常求助
解决PeoplePicker自定义排序问题
要实现名字开头匹配优先于姓氏开头的排序,你需要通过searchPeople属性覆盖组件默认的搜索逻辑,自定义排序规则:
定义自定义搜索函数,实现以下逻辑:
- 调用Microsoft Graph API获取匹配搜索词的用户列表
- 对返回的用户列表按自定义规则排序:名字(
givenName)以搜索词开头的排在最前,其次是姓氏(surname)以搜索词开头的,最后是其他包含搜索词的结果
将自定义函数传入PeoplePicker的
searchPeople属性
具体代码示例
import { PeoplePicker, UserType } from '@microsoft/mgt-react'; import { graph } from '@microsoft/mgt-element'; // 自定义搜索排序函数 const customSearchPeople = async (searchTerm: string) => { if (!searchTerm) return []; // 调用Graph API获取匹配的用户 const response = await graph.client.api('/users') .search(searchTerm) .select('id, displayName, givenName, surname, mail') .get(); const users = response.value || []; const lowerTerm = searchTerm.toLowerCase(); // 自定义排序逻辑 return users.sort((a, b) => { // 计算每个用户的匹配权重 const getWeight = (user: any) => { if (user.givenName?.toLowerCase().startsWith(lowerTerm)) return 2; if (user.surname?.toLowerCase().startsWith(lowerTerm)) return 1; return 0; }; const weightA = getWeight(a); const weightB = getWeight(b); // 权重高的排前面,权重相同则按显示名称排序 if (weightB !== weightA) { return weightB - weightA; } return a.displayName.localeCompare(b.displayName); }); }; // 在组件中使用 <PeoplePicker showMax={showMax} ref={ref} className={styles.peoplePicker} selectedPeople={data} selectionChanged={selectionChanged} blur={onBlur} userType={UserType.user} searchPeople={customSearchPeople} // 传入自定义搜索函数 />
代码说明
searchPeople属性接收一个异步函数,参数是用户输入的搜索词,返回排序后的用户数组- 排序逻辑中,通过权重区分匹配优先级:名字开头匹配权重为2,姓氏开头为1,其他匹配为0,权重高的结果靠前
- 权重相同时,按用户的
displayName做自然排序,保证结果有序
注意:确保你的应用已经正确配置了Microsoft Graph API的权限(需要User.ReadBasic.All或更高权限来读取用户信息)。
内容的提问来源于stack exchange,提问作者Gleb Gaiduk
相关产品推荐
相关产品推荐

