You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Antd Card封装为可对接Form表单的巨型自定义单选按钮选项

实现方案

核心原理是利用Antd Form的自定义组件适配规则:只要放在Form.Item下的组件接收value(当前选中值)和onChange(值变更回调)两个属性,就能自动和表单状态绑定,不需要额外的适配逻辑。

完整可运行代码

import React from 'react';
import { Form, Row, Col, Card, Button } from 'antd';
import { CheckCircleFilled } from '@ant-design/icons';

// 先定义你的单选选项配置,方便后续扩展
const OPTIONS = [
  {
    value: 'option1',
    title: '单选按钮1',
    desc: '这是单选按钮的简短描述内容。'
  },
  {
    value: 'option2',
    title: '单选按钮2',
    desc: '这是单选按钮的简短描述内容。'
  }
];

// 封装卡片单选组组件,直接对接Form规则
const CardRadioGroup = ({ value, onChange }) => {
  return (
    <Row gutter={16}>
      {OPTIONS.map(item => {
        const isChecked = value === item.value;
        return (
          <Col md={12} key={item.value}>
            <Card
              hoverable
              title={item.title}
              extra={isChecked ? <CheckCircleFilled style={{ color: '#12cc55' }} /> : null}
              onClick={() => onChange(item.value)}
              // 选中态加边框区分,可自定义样式
              style={{
                borderColor: isChecked ? '#1677ff' : '#f0f0f0',
                cursor: 'pointer'
              }}
            >
              {item.desc}
            </Card>
          </Col>
        );
      })}
    </Row>
  );
};

// 业务页面使用
export default function App() {
  const [form] = Form.useForm();

  const onFinish = (values) => {
    console.log('表单提交值:', values);
  };

  return (
    <Form form={form} layout="vertical" name="add-form" onFinish={onFinish}>
      <Form.Item
        name="type"
        label="请选择下方类型:"
        rules={[
          {
            required: true,
            message: '请选择你的类型',
          },
        ]}
      >
        {/* 直接放入封装好的组件即可,Form会自动绑定状态 */}
        <CardRadioGroup />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">提交表单</Button>
        <Button onClick={() => form.resetFields()} style={{ marginLeft: 8 }}>重置</Button>
      </Form.Item>
    </Form>
  );
}

功能说明

  • 完全兼容Antd Form所有原生能力:表单校验、赋值form.setFieldsValue()、取值form.getFieldsValue()、重置等功能和普通Radio组件完全一致
  • 保留了Card的hover阴影效果,选中态额外增加边框区分,右上角显示选中对勾
  • 后续扩展选项只需要修改OPTIONS配置数组即可,不需要改动组件逻辑

内容的提问来源于stack exchange,提问作者ProGrammer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:45:03