antd table 点击行触发radio 或 checkbox

本文介绍如何使用MobX状态管理库结合React框架,实现具有单选功能的表格组件。通过UIStore管理表格选中状态,确保每次只有一行被选中,并在表格上实现点击行切换选中状态的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 UIStore.ts (使用mobx) 1 import { observable, action, computed } from 'mobx'

 2  export class UIStore {
 3  @observable public selectedRowKeys: string[] = [] // 单选 选中的key
 4  @action
 5   public onSelectedRowKeysChange = (selectedRowKeys: string[]) => {
 6     this.selectedRowKeys = selectedRowKeys
    // do something 这里可以触发点击单选按钮选择数据
7 } 8
    // 保证单选,即数组里只有一个key 9 @action 10 public rowRadioSelected = (record: IOptions) => { 11 if (!this.selectedRowKeys.length) { 12 this.selectedRowKeys.push(record['key']) 13 } else { 14 if (this.selectedRowKeys.indexOf(record['key']) === -1) { 15 this.selectedRowKeys.splice(0, 1, record['key']) 16 } 17 } 18  } 19 } 20  export default new UIStore()

 

test.tsx
 1 import * as React from 'react'
 2 import { observer } from 'mobx-react'
 3 import UIStore from './UIStore'
 4  
 5 @observer
 6 export default class Test extends React.Component {
 7   const columns = [{
 8   title: 'Name',
 9   dataIndex: 'name',
10   render: text => <a href="#">{text}</a>,
11   }, {
12   title: 'Age',
13   dataIndex: 'age',
14   }, {
15   title: 'Address',
16   dataIndex: 'address',
17   }]
18  
19   const data = [{
20   key: '1',
21   name: 'John Brown',
22   age: 32,
23   address: 'New York No. 1 Lake Park',
24   }, {
25   key: '2',
26   name: 'Jim Green',
27   age: 42,
28   address: 'London No. 1 Lake Park',
29   }, {
30   key: '3',
31   name: 'Joe Black',
32   age: 32,
33   address: 'Sidney No. 1 Lake Park',
34   }, {
35   key: '4',
36   name: 'Disabled User',
37   age: 99,
38   address: 'Sidney No. 1 Lake Park',  
39  }]
40  
41  render () {
42   
43    const rowRadioSelection: TableRowSelection<IOptions> = {  // IOptions 是每行数据的类型
44      type: 'radio',
45      selectedRowKeys: toJS(UIStore.selectedRowKeys), 
46      onChange: UIStore.onSelectedRowKeysChange,
47     }
48   return (
49   <Table 
50   rowKey={(_, i) => `${i}`}
51   columns={columns}
52   dataSource={data}
53    rowSelection={rowRadioSelection}
54     onRow={record => {
55       return {
56         onClick: () => {
57        UIStore.rowRadioSelected(record)
58       },
59      }
60       }
61    }
62  />
63 )}
64 }
 
 
 

参考: https://codesandbox.io/s/000vqw38rl

 

转载于:https://www.cnblogs.com/aloehui/p/10178396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值