Skip to content

React 单选行 radio

配置 type: 'radio' 列实现行单选(互斥),通过 onRadioChange 监听、ref 上的 getSelectedRadio() / setSelectedRadio() 读写选中行。

使用的 API

ts
type Column = {
  key: string;  // 列标识(必填)
  title: string;  // 列标题(必填)
  width: number;  // 列宽(必填)
  type: 'radio';  // 特殊列类型:单选列
  fixed?: 'left' | 'right';  // 冻结列
}

type Options = {
  list: T[];  // 数据列表
  itemKey: string;  // 行唯一标识字段名
  estimatedSize: number;  // 行预估高度(px)
  onRadioChange?: (row: T) => void;  // 选中行变化回调
}

// 实例方法(ref 上调用)
tableRef.current?.getSelectedRadio();
tableRef.current?.setSelectedRadio(rowKey);  // 传 null 清除

示例

微应用尚未挂载。

源码

点击查看源码
tsx
import React from 'react';
import { VirtTableReact, type ReactTableColumn, type VirtTableRef } from '@virt-table/react';
import { faker } from '@faker-js/faker';

interface Row extends Record<string, unknown> {
  id: number;
  name: string;
  city: string;
}

const columns: ReactTableColumn<Row>[] = [
  { key: 'radio', title: '', width: 50, type: 'radio', fixed: 'left' },
  { key: 'id', title: 'ID', width: 80 },
  { key: 'name', title: '姓名', width: 220 },
  { key: 'city', title: '城市', width: 220 },
];

const list: Row[] = Array.from({ length: 500 }, (_, i) => ({
  id: i + 1,
  name: faker.person.fullName(),
  city: faker.location.city(),
}));

export default function RadioTable() {
  const tableRef = React.useRef<VirtTableRef>(null);
  const [out, setOut] = React.useState('未选中');

  return (
    <div className="demo-wrapper">
      <h3 className="demo-title">React 单选行 radio</h3>
      <div className="virt-table-controls">
        <button
          type="button"
          className="virt-table-btn virt-table-btn-primary"
          onClick={() => {
            const r = tableRef.current?.getSelectedRadio() as Row | null | undefined;
            setOut(r ? `当前:${r.name}(id=${r.id})` : '未选中');
          }}
        >
          获取当前选中
        </button>
        <button
          type="button"
          className="virt-table-btn"
          onClick={() => {
            tableRef.current?.setSelectedRadio(null);
            setOut('未选中');
          }}
        >
          清除
        </button>
        <span className="demo-note">{out}</span>
      </div>
      <div style={{ width: 620, height: 480 }} className="demo-container">
        <VirtTableReact
          ref={tableRef}
          columns={columns}
          options={{
            list,
            itemKey: 'id',
            estimatedSize: 40,
            buffer: 6,
            border: true,
            onRadioChange: (row) => setOut(`选中:${(row as Row).name}`),
          }}
        />
      </div>
    </div>
  );
}