问题描述
我正在尝试使用 fluent ui 中的 tagPicker。我使用该站点的示例作为起点: https://developer.microsoft.com/en-us/fluentui#/controls/web/pickers
问题是我拥有的对象有 3 个道具。数组中的对象是 {Code:'string',Title:'string',Category:'string'}。我正在使用具有 useEffect 的状态来获取数据。到目前为止工作正常,问题是建议被呈现为空白。它过滤项目但不显示我想要的道具。
这是我的代码:
import * as React from 'react';
import {
TagPicker,IBasePicker,ITag,IInputProps,IBasePickerSuggestionsprops,} from 'office-ui-fabric-react/lib/Pickers';
import { mergeStyles } from 'office-ui-fabric-react/lib/Styling';
const inputProps: IInputProps = {
onBlur: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onBlur called'),onFocus: (ev: React.FocusEvent<HTMLInputElement>) => console.log('onFocus called'),'aria-label': 'Tag picker',};
const pickerSuggestionsprops: IBasePickerSuggestionsprops = {
suggestionsHeaderText: 'Suggested tags',noresultsFoundText: 'No color tags found',};
const url="url_data"
export const TestPicker: React.FunctionComponent = () => {
const getTextFromItem = (item) => item.Code;
const [state,setStateObj] = React.useState({items:[],isLoading:true})
// All pickers extend from BasePicker specifying the item type.
React.useEffect(()=>{
if (!state.isLoading) {
return
} else {
caches.open('cache')
.then(async cache=> {
return cache.match(url);
})
.then(async data=>{
return await data.text()
})
.then(data=>{
const state = JSON.parse(data).data
setStateObj({items:state,isLoading:false})
})
}
},[state.isLoading])
const filterSuggestedTags = (filterText: string,tagList: ITag[]): ITag[] => {
return filterText
? state.items.filter(
tag => tag.Code.toLowerCase().indexOf(filterText.toLowerCase()) === 0 && !listContainsTagList(tag,tagList),).slice(0,11) : [];
};
const listContainsTagList = (tag,state?) => {
if (!state.items || !state.items.length || state.items.length === 0) {
return false;
}
return state.items.some(compareTag => compareTag.key === tag.key);
};
return (
<div>
Filter items in suggestions: This picker will filter added items from the search suggestions.
<TagPicker
removeButtonAriaLabel="Remove"
onResolveSuggestions={filterSuggestedTags}
getTextFromItem={getTextFromItem}
pickerSuggestionsprops={pickerSuggestionsprops}
itemLimit={1}
inputProps={inputProps}
/>
</div>
);
};
解决方法
我刚知道,我需要映射项目以遵循示例中的 {key,name}。现在它可以工作了。
setStateObj({items:state.map(item => ({ key: item,name: item.Code })),isLoading:false})