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 @action10 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 => {text},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 是每行数据的类型44 type: 'radio',45 selectedRowKeys: toJS(UIStore.selectedRowKeys), 46 onChange: UIStore.onSelectedRowKeysChange,47 }48 return (49 `${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 }
参考: