Office UI Fabric React TagPicker新项

时间:2018-05-21 15:25:00

标签: reactjs office-ui-fabric

摘要

有人知道如何让UI Fabric React TagPicker在建议中输入的内容中添加新项目吗?

我想要向服务发送一个AJAX请求,以便在后端添加新项目。

所需功能

如果有人在选项器中输入的内容中没有选项,那么他们可以选择将其添加为新选项,并调用其他一些代码将此新选项添加​​到后端API ..

到目前为止我尝试了什么

我已经能够在pickerSuggestionsProps.onRenderNoResultFound上添加一个带有点击处理程序的按钮,该处理程序将运行一些代码来添加关键字,但这需要挂钩到onChange以跟踪用户输入了,但这打破了建议的选择(当处理onChange时,用户无法从选择器下面显示的列表中选择建议。)

2 个答案:

答案 0 :(得分:0)

我建议在GitHub上改进此控件。

codepen是我从那里得到的答复中分叉出来的,显示了目前如何完成此操作...

const {
TagPicker,  Fabric, mergeStyles
} = window.Fabric;

const _testTags: ITag[] = [
  'black',
  'blue',
  'brown',
  'cyan',
  'green',
  'magenta',
  'mauve',
  'orange',
  'pink',
  'purple',
  'red',
  'rose',
  'violet',
  'white',
  'yellow'
].map(item => ({ key: item, name: item, isNewItem: false }));

const newItem = mergeStyles({ color: '#f00', background: '#ddf', padding: '10px' });
const existingItem = mergeStyles({ color: '#222', padding: '10px' });

class TagPickerBasicExample extends React.Component<{}, {}> {
  private picker = React.createRef<IBasePicker<ITag>>();

  public render() {
    return <TagPicker
              onResolveSuggestions={this.onResolveSuggestions}
              componentRef={this.picker}
              onRenderSuggestionsItem={this.onRenderSuggestionsItem}
              onItemSelected={this.onItemSelected}
            />;
  }

  private onRenderSuggestionsItem = (props: any, itemProps: any): JSX.Element => {
    console.log({props, itemProps})
    return <div className={props.isNewItem ? newItem : existingItem} key={props.key}>
      {props.name}
      </div>;
  };

  private onResolveSuggestions = (filterText: string, tagList: ITag[]): ITag[] => {
     console.log({filterText, tagList});

    const existingMatches = filterText
      ? _testTags
          .filter(tag => tag.name.toLowerCase().indexOf(filterText.toLowerCase()) === 0)
          .filter(tag => !this.listContainsDocument(tag, tagList))
      : [];

    return existingMatches.some(a=> a.key === filterText) ? 
    existingMatches :
    [{ key: filterText, name: filterText, isNewItem: true } as ITag].concat(existingMatches);
  };

  private onItemSelected = (item: ITag): ITag | null => {
    if(item && item.isNewItem) {
      alert("New item added, make any necessary backend calls.");
    }
    return item;
  };

  private listContainsDocument(tag: ITag, tagList?: ITag[]) {
    if (!tagList || !tagList.length || tagList.length === 0) {
      return false;
    }
    return tagList.filter(compareTag => compareTag.key === tag.key).length > 0;
  }
}

ReactDOM.render(
  <Fabric>
    <TagPickerBasicExample />
  </Fabric>,
  document.getElementById('content')
);

希望它会有所帮助-确实对我有用。

答案 1 :(得分:0)

结果证明这很简单。您只需要将createGenericItem属性设置为返回虚拟项目的方法即可:

createGenericItem={(input: string) => {
  return { key: '', name: input} as ITag;
}}