问题描述
Selection Component 的流畅 UI 具有让用户选择单个或多个项目的属性。但是,我没有看到一种直接的方法来限制用户选择某些最大数量的项目。有没有办法做到这一点?
我已尝试通过使用 Selection 组件的 onSelectionChanged 事件来解决此问题。但解决方案和行为似乎并不完美。
代码笔链接:https://codepen.io/sakamati/pen/poRryqa
const { useRef } = React;
const { DetailsList,DetailsListLayoutMode,Selection,SelectionMode,IColumn,MarqueeSelection } = window.FluentUIReact;
interface IDetailsListDocumentsExampleState {
columns: IColumn[];
items: IDocument[];
selectionDetails: string;
isModalSelection: boolean;
isCompactMode: boolean;
announcedMessage?: string;
}
interface IDocument {
key: number;
value: string;
}
class DetailsListDocumentsExample extends React.Component<{},IDetailsListDocumentsExampleState> {
private _selection: Selection;
private _allItems: IDocument[];
private readonly _maxSelectable = 10;
public constructor(props: {}) {
super(props);
let a = [];
for(let i=0;i<50; i++){
a.push({key:i,value:'Abc '+i});
}
this._allItems = a;
const columns: IColumn[] = [
{
key: 'column1',name: 'Key',fieldName: 'key',minWidth: 160,maxWidth: 160,isRowHeader: true,isResizable: true,data: 'number',},{
key: 'column2',name: 'value',fieldName: 'value',minWidth: 210,maxWidth: 350,data: 'string',}
];
this.state = {
items: this._allItems,columns: columns,selectionDetails: this._getSelectionDetails(),isModalSelection: false,isCompactMode: false,announcedMessage: undefined,};
this._selection = new Selection({
onSelectionChanged: () => {
console.log("onSelectionChanged Invoked!");
const c = this._selection.getSelectedCount();
//alert(this._selection.getSelectedCount());
if(c>this._maxSelectable){
const indices = this._selection.getSelectedindices();
this._selection.toggleRangeSelected(indices[this._maxSelectable],indices.length-this._maxSelectable);
}
console.log(c);
},});
}
public render() {
const { columns,isCompactMode,items,selectionDetails,isModalSelection,announcedMessage } = this.state;
return (
<MarqueeSelection selection={this._selection}>
<DetailsList
items={items}
columns={columns}
selectionMode={SelectionMode.multiple}
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
selection={this._selection}
selectionPreservedOnEmptyClick={true}
onItemInvoked={this._onItemInvoked}
/>
</MarqueeSelection>
);
}
private _onItemInvoked(item: any): void {
alert('Item invoked: ' + item.value);
}
private _getSelectionDetails(): string {
/*const selectionCount = this._selection.getSelectedCount();
switch (selectionCount) {
case 0:
return 'No items selected';
case 1:
return '1 item selected: ' + (this._selection.getSelection()[0] as IDocument).key;
default:
return `${selectionCount} items selected`;
}*/
return "Hello";
}
}
ReactDOM.render(<DetailsListDocumentsExample />,document.getElementById("root"))
解决方法
当您有一定数量的项目时,您可以清除选择:
const clearSelection = () => {
currentSelection.setAllSelected(false);
};