简体   繁体   中英

react app how can I set the state of the radio button in an antd table?

I try to understand antd.

I have here from the documentation Table Example 3. When the radio button is clicked, this state is set and the row is selected. If i clicked a cell of a row, the row should also be selected and the ckeck state of the radio button should be set.

Does anyone have any idea how to do that?

import React from 'react';
import { Table } from 'antd';
import 'antd/dist/antd.css';

const columns = [
    {
        title: 'Name',
        dataIndex: 'name',
        render: (text: string) => <a>{text}</a>,
    },
    {
        title: 'Age',
        dataIndex: 'age',
    },
    {
        title: 'Address',
        dataIndex: 'address',
    },
];

interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
}

const data: DataType[] = [
    {
        key: '1',
        name: 'John Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
    },
    {
        key: '2',
        name: 'Jim Green',
        age: 42,
        address: 'London No. 1 Lake Park',
    },
    {
        key: '3',
        name: 'Joe Black',
        age: 32,
        address: 'Sidney No. 1 Lake Park',
    },
    {
        key: '4',
        name: 'Disabled User',
        age: 99,
        address: 'Sidney No. 1 Lake Park',
    },
];

// rowSelection object indicates the need for row selection
const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
};


export default function TableDemo() {

    return (
        <React.Fragment>
            <Table
                rowSelection={{
                    type: 'radio',
                    ...rowSelection,
                }}
                columns={columns}
                dataSource={data}
                
            />

        </React.Fragment>
    );
}

Current v4 docs for table are pretty extensive. Buried in there is this.

"Rows can be selectable by making first column as a selectable column. You can use rowSelection.type to set selection type. Default is checkbox.

selection happens when clicking checkbox by default. You can see https://codesandbox.io/s/000vqw38rl if you need row-click selection behavior."

Seems like what you're looking for. Easy to miss, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM