antd table 點擊行觸發radio 或 checkbox

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

 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數組

相關文章
相關標籤/搜索