react如何获取当前行id
获取当前行ID的方法
在React中获取当前行的ID通常发生在列表渲染或表格操作场景中。以下是几种常见实现方式:
通过事件处理函数传递
在渲染列表时,将ID作为参数传递给事件处理函数:

const rows = [{id: 1, name: 'A'}, {id: 2, name: 'B'}];
function handleClick(id) {
console.log('Current row ID:', id);
}
return (
<ul>
{rows.map(row => (
<li key={row.id} onClick={() => handleClick(row.id)}>
{row.name}
</li>
))}
</ul>
);
使用data-attribute
通过HTML5的data属性存储ID,通过事件对象获取:
function handleClick(e) {
const id = e.currentTarget.dataset.id;
console.log('Current row ID:', id);
}
return (
<button data-id="123" onClick={handleClick}>
Get ID
</button>
);
类组件中的绑定方式
在类组件中可通过bind或箭头函数保留this上下文:

class Row extends React.Component {
handleClick = (id) => {
console.log('Current row ID:', id);
};
render() {
return this.props.data.map(item => (
<div key={item.id} onClick={() => this.handleClick(item.id)}>
{item.text}
</div>
));
}
}
动态表格中的行ID获取
处理表格行点击时,推荐使用事件委托:
function Table({ data }) {
const handleRowClick = (e) => {
const rowId = e.currentTarget.getAttribute('data-rowid');
console.log('Clicked row ID:', rowId);
};
return (
<table>
<tbody>
{data.map(row => (
<tr key={row.id} data-rowid={row.id} onClick={handleRowClick}>
<td>{row.content}</td>
</tr>
))}
</tbody>
</table>
);
}
使用自定义Hook
封装可复用的行ID获取逻辑:
function useRowId() {
const [currentId, setCurrentId] = useState(null);
const handleRowSelect = (id) => {
setCurrentId(id);
console.log('Selected ID:', id);
};
return { currentId, handleRowSelect };
}
// 使用示例
function ListComponent() {
const { handleRowSelect } = useRowId();
return <div onClick={() => handleRowSelect(5)}>Click me</div>;
}
注意事项
- 避免在渲染时直接执行逻辑,应通过事件触发
- 动态生成的key属性不会暴露给组件props
- 大数据量列表建议使用事件委托优化性能
- 考虑添加ARIA属性增强无障碍访问
以上方法可根据具体场景选择使用,事件参数传递是最直接的方案,而自定义Hook更适合复杂状态管理场景。






