React/NextUI表格内Button首次点击无法触发onPress问题排查
问题原因及解决方案
核心原因
NextUI的Table.Row组件默认开启了选中功能,首次点击Button时,事件会先被Row的选中逻辑捕获处理,导致Button的onPress事件被屏蔽;第二次点击时,Row已处于选中状态,不会再触发选中逻辑,Button的点击事件就能正常执行。而Table外的Button没有这个层级的事件拦截,所以首次点击即可正常响应。
解决方案
方案1:禁用Row的默认选中功能
给Table.Row添加isSelectable={false}属性,直接避免事件冲突:
修改后的完整代码:
"use client" import * as React from 'react'; import { Button, Table } from "@nextui-org/react"; export default class Thing extends React.Component<any,any> { constructor(props : any) { super(props); this.state = { rows: [ { "id": 1 }, ], columns : [ { key: "actions", label: "ACTIONS", }, ], }; } render() { return ( <> <Table aria-label="Example Table" > <Table.Header columns={this.state.columns}> {(column: any) => ( <Table.Column key={column.key}>{column.label}</Table.Column> )} </Table.Header> <Table.Body items={this.state.rows}> {(item : any) => ( <Table.Row key={item.id} isSelectable={false}> {(key : any) => <Table.Cell css={{ maxWidth: "500px", }}> <Button auto onPress={() => { console.log("pressed") }}> Info </Button> </Table.Cell> } </Table.Row> )} </Table.Body> </Table> </> ); } };
方案2:保留Row选中功能,阻止Button事件冒泡
如果需要保留Row的选中交互,可以在Button的点击事件中阻止事件向上冒泡:
<Button auto onPress={(e) => { e.stopPropagation(); console.log("pressed"); }}> Info </Button>
内容的提问来源于stack exchange,提问作者Ryan Hayward
相关产品推荐
相关产品推荐

