React中PrimeReact表格行数据获取问题:点击行获取ID与名称
解决方案
场景1:点击任意行时获取该行的name字段
直接使用DataTable的onRowClick事件,它会返回当前点击行的完整数据对象,从中提取name即可:
<DataTable ref={dt} value={rows} selection={selectedProducts} onSelectionChange={(e) => {setEmployeeId(e.value)}} dataKey="id" paginator rows={10} currentPageReportTemplate="Showing {first} to {last} of {totalRecords} products" globalFilter={globalFilter} responsiveLayout="scroll" // 新增行点击事件 onRowClick={(e) => { // e.data就是当前点击的行数据对象 const rowName = e.data.name; console.log(rowName); // 这里可以把name存到状态里 // setEmployeeName(rowName); }} > <Column selectionMode="multiple" headerStyle={{ width: '2rem' }} exportable={false}></Column> <Column header="Action" body={actionBodyTemplate} exportable={false} style={{ minWidth: '2rem' }}></Column> <Column field="name" header='Name' sortable style={{ minWidth: '2rem' }}></Column> <Column field="workingTime" header='Working Time' sortable style={{ minWidth: '2rem' }}></Column> </DataTable>
场景2:多选模式下,获取所有选中行的name字段
如果需要在多选时拿到所有选中行的name,可以在onSelectionChange里遍历选中数组:
onSelectionChange={(e) => { // e.value是选中的所有行对象组成的数组 const selectedNames = e.value.map(row => row.name); console.log(selectedNames); // 若要存单个值,可根据需求取第一个或其他逻辑 // if(e.value.length > 0) setEmployeeId(e.value[0].id); }}
关键说明
onRowClick事件专注于单行点击交互,返回的e.data包含当前行的所有字段(包括id和name),适合单行操作场景。- 原代码中
onSelectionChange的e.value是选中行的数组,而非单个行对象,所以直接拿e.value无法获取单个行的name,需要遍历或取数组中的元素。
内容的提问来源于stack exchange,提问作者Developer007
相关产品推荐
相关产品推荐

