从NextUI Table获取选中项遇类型错误的技术求助
问题:NextUI表格多选选中项获取失败及类型错误
背景
我是JS和NextUI纯新手,平时用C#和DotNET开发。现在要做一个带多选功能的表格,点击按钮时把所有选中项传给一个接收JSON数组的use server函数,但卡在获取选中项这一步。
尝试的代码
// ... const [selectedKeys, setSelectedKeys] = React.useState(new Set([])); return ( <section className="flex flex-col items-center justify-center gap-4 py-8 md:py-10"> <div className="inline-block max-w-lg text-center justify-center"> <h2 className={subtitle({ class: "mt-4" })}> Bitte die zu entfernenden Rezensionen auswählen: </h2> </div> <div className="flex flex-col gap-3"> <Table color="primary" selectionMode="multiple" aria-label="Example static collection table" isStriped selectedKeys={selectedKeys} onSelectionChange={setSelectedKeys} > <TableHeader columns={columns}> {(column) => <TableColumn key={column.key}>{column.label}</TableColumn>} </TableHeader> <TableBody items={reviews}> {(item) => ( <TableRow key={item.key}> {(columnKey) => <TableCell>{getKeyValue(item, columnKey)}</TableCell>} </TableRow> )} </TableBody> </Table> ); // ...
说明:item.key为数字,与NextUI文档及教程中的设定一致。
遇到的错误
VS Code类型错误提示
Type 'Dispatch<SetStateAction<Set<never>>>' is not assignable to type '(keys: Selection) => void'. Types of parameters 'value' and 'keys' are incompatible. Type 'Selection' is not assignable to type 'SetStateAction<Set<never>>'. Type 'string' is not assignable to type 'SetStateAction<Set<never>>'.ts(2322) selection.d.ts(39, 3): The expected type comes from property 'onSelectionChange' which is declared here on type 'IntrinsicAttributes & MergeWithAs<Omit<DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>, "ref">, Omit<...>, TableProps, "table">'
运行时错误

解决方案
1. 修正状态类型定义
初始状态未指定类型,TS自动推断为Set<never>,和NextUI的Selection类型冲突。明确指定状态为数字集合:
const [selectedKeys, setSelectedKeys] = React.useState<Set<number>>(new Set([]));
2. 统一处理选中项格式
NextUI的onSelectionChange返回的keys可能是单个值(单选场景)或集合(多选场景),需要统一转换成Set:
const handleSelectionChange = (keys: Selection) => { const newSelectedKeys = typeof keys === 'string' || typeof keys === 'number' ? new Set([keys]) : keys; setSelectedKeys(newSelectedKeys as Set<number>); };
然后把Table组件的onSelectionChange替换为这个处理函数:
<Table // 其他属性保持不变 onSelectionChange={handleSelectionChange} >
3. 传递选中项给服务端函数
点击按钮时,把Set转换成数组,再转成JSON格式传给use server函数:
async function handleSubmit() { const selectedIds = Array.from(selectedKeys); await yourServerFunction(JSON.stringify(selectedIds)); }
内容的提问来源于stack exchange,提问作者Tim Oppitz
相关产品推荐
相关产品推荐

