如何通过函数重置Shopify Polaris IndexTable的选中状态
如何重置Shopify Polaris IndexTable的选中状态?
我需要通过函数重置Shopify Polaris IndexTable的选中状态,尝试过重新渲染组件、修改selectedItemsCount和itemCount的值,但效果不稳定。Polaris通过useIndexResourceState钩子管理选中状态,但相关文档不足。
示例代码如下:
import { IndexTable, LegacyCard, useIndexResourceState, Text, Button, } from '@shopify/polaris'; import React from 'react'; function SimpleIndexTableExample() { const orders = [ { id: '1020', order: '#1020', }, { id: '1019', order: '#1019', }, { id: '1018', order: '#1018', }, ]; const resourceName = { singular: 'order', plural: 'orders', }; const {selectedResources, allResourcesSelected, handleSelectionChange} = useIndexResourceState(orders); const resetSelection = () => { console.log('Reset selection. No items selected anymore.') } const rowMarkup = orders.map( ( {id, order}, index, ) => ( <IndexTable.Row id={id} key={id} selected={selectedResources.includes(id)} position={index} > <IndexTable.Cell> <Text variant="bodyMd" fontWeight="bold" as="span"> {order} </Text> </IndexTable.Cell> </IndexTable.Row> ), ); return ( <LegacyCard> <IndexTable resourceName={resourceName} itemCount={orders.length} selectedItemsCount={ allResourcesSelected ? 'All' : selectedResources.length } onSelectionChange={handleSelectionChange} headings={[ {title: 'Order'}, ]} > {rowMarkup} </IndexTable> <Button onClick={resetSelection}>Reset selection</Button> </LegacyCard> ); } export default SimpleIndexTableExample;
解决方案
直接使用useIndexResourceState返回的handleSelectionChange方法即可稳定重置选中状态,无需强行修改组件属性或重新渲染。修改resetSelection函数如下:
const resetSelection = () => { handleSelectionChange({selection: []}); };
原理说明
handleSelectionChange是useIndexResourceState提供的状态更新方法,它接受包含selection(选中项ID数组)的对象作为参数。当传入空数组时,钩子会自动更新selectedResources为空数组,并将allResourcesSelected设为false,同步更新IndexTable的选中状态。
如果需要明确指定选择模式(比如多选),也可以传入selectionType参数:
const resetSelection = () => { handleSelectionChange({ selection: [], selectionType: 'multiple', }); };
修改后点击"Reset selection"按钮即可清空所有选中项,效果稳定。
内容的提问来源于stack exchange,提问作者Smlok
相关产品推荐
相关产品推荐

