Arco Design React 单选框 Radio 组件实战指南:API 详解、受控原理与源码级解析
Arco Design React 单选框 Radio 组件实战指南:API 详解、受控原理与源码级解析
在表单场景中,单选框(Radio)用于在一组相关且互斥的数据里让用户只能选择一个选项。本文以 Arco Design React 组件库中 Radio 组件 的官方文档为主体,结合仓库内 radio.tsx、group.tsx、interface.ts 等源码与 单元测试,系统讲解 Radio 与 Radio.Group 的全部 API、两种单选组配置方式、按钮形态、尺寸体系、自定义渲染,以及受控/非受控的底层实现,帮助你直接上手并在项目中用得明白、改得放心。
一、组件定位:什么场景该用 Radio
Radio 是一个典型的数据输入(Data Entry)组件。官方文档对其语义的定义是:在一组相关且互斥的数据中,用户仅能选择一个选项。与之对比,多选场景应使用 Checkbox;在空间有限、选项很多(超过 5 个)时,则应优先考虑 Select 下拉选择。
在 Arco Design 中,Radio 以两种形态对外暴露:
Radio:单个单选框,可独立使用(配合checked/defaultChecked);Radio.Group:单选组,负责管理一组 Radio 的互斥选中状态,既可以通过children传入多个Radio,也可以通过options数组一键生成。
Radio.Group 通过静态属性挂载在 Radio 上,因此使用方式为 const RadioGroup = Radio.Group;,这与组件入口 index.tsx 中的导出(Radio.Group = Group;,见 radio.tsx)一致。
二、Radio 组件 API 详解
Radio 继承原生 <label> 标签的 HTML 属性(2.2.0 版本起支持原生标签属性透传),其类型定义见 interface.ts。官方 API 表如下:
| 参数 | 描述 | 类型 | 默认值 |
|---|---|---|---|
checked |
是否选中(受控模式) | boolean |
- |
defaultChecked |
初始是否选中 | boolean |
- |
disabled |
是否禁用 | boolean |
- |
className |
节点类名 | string | string[] |
- |
style |
节点样式 | CSSProperties |
- |
value |
控件的 value |
T |
- |
onChange |
值变化的回调 | (checked: boolean, event: ChangeEvent) => void |
- |
几个需要重点说明的细节:
1. 受控与 defaultChecked 的关系:checked 一旦传入即进入受控模式,组件的选中态完全由外部驱动;defaultChecked 仅作用于首次渲染。二者的切换在源码中由 useMergeValue 钩子完成(见 useMergeValue.ts):mergedValue = isUndefined(value) ? stateValue : value,即只有外部 value 为 undefined 时才回落到内部 state;同时,若外部值从有值变为 undefined,内部 state 会被同步更新。
2. onChange 只在"未选中 → 选中"时触发:从 radio.tsx 的实现可以看出,点击时若当前未选中,会先 setChecked(true),随后调用 onChange(true, event);由于单选语义下"取消选中"不被允许,重复点击已选中的 Radio 不会再次触发回调。
3. children 可以是函数(2.29.0 起,2.66.14 起增加 disabled 参数):children 支持传入 (value: { checked: boolean; disabled: boolean }) => ReactNode(类型见 interface.ts),用于完全自定义节点内容,本文第六节有完整示例。
4. value 为任意泛型 T:在独立使用时 value 仅作为表单值透传到原生 input;在 Group 内部,它才是判断选中态的关键依据。
三、Radio.Group 组件 API 详解
Radio.Group 的属性定义见 interface.ts,官方 API 表如下:
| 参数 | 描述 | 类型 | 默认值 |
|---|---|---|---|
disabled |
禁用 | boolean |
- |
name |
Radio 的 name |
string |
- |
direction |
方向 | 'vertical' | 'horizontal' |
horizontal |
size |
按钮类型的单选框尺寸(只在按钮类型下生效) | 'small' | 'default' | 'large' | 'mini' |
- |
type |
单选的类型,是单选还是按钮 | 'radio' | 'button' |
radio |
className |
节点类名 | string | string[] |
- |
defaultValue |
默认选中的值 | any |
- |
options |
以数组配置的形式来设置单选组 | (string | number | { label: ReactNode; value: any; disabled?: boolean })[] |
- |
style |
节点样式 | CSSProperties |
- |
value |
选中的值(受控模式) | any |
- |
onChange |
点击单选的回调 | (value: any, event: ChangeEvent) => void |
- |
补充说明:
defaultProps中的默认值(见 group.tsx):type: 'radio'、mode: 'outline'、direction: 'horizontal'。其中mode属性('outline' | 'fill')在 README 中未列出,但存在于源码类型定义中,用于按钮形态的填充/描边样式切换,可按需使用。size仅对按钮类型生效:若Radio.Group未显式设置size,会回落到 ConfigProvider 提供的全局size(源码const size = props.size || ctxSize;,见 group.tsx)。name会被透传到内部每个 Radio 的原生 input(见 radio.tsx),用于原生表单语义分组,配合:focus-visible选择器可实现键盘焦点样式。options与children二选一:源码中options && isArray(options)时用 options 渲染,否则渲染children(见 group.tsx)。对象型 option 会单独支持disabled并优先取自身disabled,字符串/数字型 option 则整体继承 Group 的disabled。
单选组的工作原理:Context 传递
Radio.Group 的互斥选中状态并非通过克隆 children 注入 props 实现,而是基于 React Context:
- Group 内部维护一个受控/非受控的
value(同样基于useMergeValue),并通过<RadioGroupContext.Provider>向下传递{ onChangeValue, type, value, disabled, group: true, name }(见 group.tsx); - 每个
Radio在useContext(RadioGroupContext)后,若context.group为真,则用context.value === props.value计算自己的选中态,并用"自身 disabled 优先、否则继承 Group disabled"的规则确定禁用态(见 radio.tsx); - 点击任意 Radio 时,通过
context.onChangeValue(value, event)上报给 Group,Group 在onChangeValue中判断"非受控时更新内部 state + 统一触发 Group 的onChange"(见 group.tsx)。
这正是单选组"点击任意一项,整组状态联动"的底层机制。若需要脱离 Group 使用独立的 Radio 上下文(例如在自定义弹层中隔离状态),组件还导出了 ClearRadioGroupContext(见 index.tsx)。
四、基础用法与受控示例
最简单的独立 Radio 用法如下(源自仓库示例 basic.md):
import { Radio, Space } from '@arco-design/web-react';
const App = () => {
return (
<Space size={40}>
<Radio>Radio</Radio>
<Radio checked disabled>
Disabled Radio
</Radio>
</Space>
);
};
export default App;
若需受控使用,传入 checked 并在 onChange 中更新外部状态即可。单元测试 index.test.tsx 验证了三种核心行为:点击未选中项后节点获得 arco-radio-checked 类名;defaultChecked 首次渲染即选中;受控模式下即使触发 onChange,DOM 类名也不会变化(选中态完全由外部 checked 决定)。
五、Radio.Group 的两种配置方式:children 与 options
单选组支持两种写法,对应仓库示例 radio_group.md:
import { Radio } from '@arco-design/web-react';
const RadioGroup = Radio.Group;
const App = () => {
return (
<div>
{/* 方式一:children 方式,可自由组合、按需禁用 */}
<RadioGroup defaultValue="a" style={{ marginBottom: 20 }}>
<Radio value="a">A</Radio>
<Radio value="b">B</Radio>
<Radio value="c">C</Radio>
<Radio disabled value="d">
D
</Radio>
</RadioGroup>
<br />
{/* 方式二:字符串数组 */}
<RadioGroup options={['A', 'B', 'C', 'D']} style={{ marginBottom: 20 }} />
<br />
{/* 方式二:对象数组,可配置 label / value / disabled */}
<RadioGroup
options={[
{ label: 'A', value: 'a' },
{ label: 'B', value: 'b' },
{ label: 'C', value: 'c' },
{ label: 'D', value: 'd', disabled: true },
]}
/>
</div>
);
};
export default App;
两种方式在实际项目中各有适用场景:children 方式灵活,适合选项需要差异化渲染(如图标、Tooltip 包裹,见 Radio.story.tsx);options 方式声明式更强,适合数据驱动渲染,也便于从接口数据直接映射。
禁用态的组合规则值得留意:Group 级 disabled 会整体禁用所有子项;但单个 Radio 自身的 disabled 优先级更高——测试 group.test.tsx 验证了"对象 options 中单独 disabled 的项可独立禁用,而其它项仍可交互"的行为(该能力在 2.62.0 版本修复了 Group 禁用后内部 Radio 单独禁用配置失效的问题)。
六、方向、按钮形态与尺寸体系
1. 竖直排列:direction="vertical"
默认 direction="horizontal" 水平排列;设置为 'vertical' 后单选组变为纵向堆叠(见 direction.md):
<RadioGroup direction="vertical" defaultValue="a">
<Radio value="a">A</Radio>
<Radio value="b">B</Radio>
<Radio value="c">C</Radio>
<Radio disabled value="d">
D
</Radio>
</RadioGroup>
从样式层看,.arco-radio-group-direction-vertical 会将内部 Radio 改为 display: block 并去除右间距(见 index.less)。2.66.12 版本还修复了 type="button" 与 direction="vertical" 组合时按钮仍水平排列的问题,因此按钮形态也支持纵向排列。
2. 按钮形态:type="button"
设置 type="button" 后,单选组以分段按钮组形式呈现(见 radio_button.md):
<RadioGroup
type="button"
name="lang"
defaultValue="Guangzhou"
style={{ marginRight: 20, marginBottom: 20 }}
>
<Radio value="Beijing">Beijing</Radio>
<Radio value="Shanghai">Shanghai</Radio>
<Radio disabled value="Guangzhou">
Guangzhou
</Radio>
<Radio value="Shenzhen">Shenzhen</Radio>
</RadioGroup>
按钮形态的内部结构对应源码中的分支:context.type === 'radio' 时渲染圆形 mask 指示器,context.type === 'button' 时渲染 .arco-radio-button-inner(见 radio.tsx)。样式方面,按钮组外层容器通过伪元素提供底色与圆角,相邻按钮之间用 1px 分割线区分,选中与悬停项的分割线自动隐藏(见 index.less)。
3. 四种尺寸:size
按钮类型提供 mini、small、default、large 四个尺寸(见 size.md):
const options = [
{ value: 'Beijing', label: 'Beijing' },
{ value: 'Shanghai', label: 'Shanghai' },
{ value: 'Guangzhou', label: 'Guangzhou', disabled: true },
{ value: 'Shenzhen', label: 'Shenzhen' },
];
<RadioGroup options={options} size="mini" type="button" defaultValue="Beijing" />
<RadioGroup options={options} size="small" type="button" defaultValue="Beijing" />
<RadioGroup options={options} size="default" type="button" defaultValue="Beijing" />
<RadioGroup options={options} size="large" type="button" defaultValue="Beijing" />
尺寸通过类名 ${prefixCls}-size-${size} 实现,与 @radio-size-mini-height、@radio-size-small-height 等 token 对应(见 token.less)。
4. 图标组合
children 为普通 ReactNode 时,图标可以与文字一起渲染(见 icon.md)。仓库示例在 Radio 的 children 中混入图片与品牌名,实现"图文单选"效果。
七、自定义节点内容:children 函数渲染(2.29.0+)
当 children 为函数时,Radio 会以 { checked, disabled } 为参数调用它,实现完全自定义的选中态样式。这是实现"卡片式单选""自定义按钮单选"的标准方案(见 custom_render.md):
import { Radio, Button, Space, Typography } from '@arco-design/web-react';
const App = () => {
return (
<div>
{/* 按钮式自定义:选中时 Button 变为 primary */}
<Radio.Group defaultValue={'Beijing'} name="button-radio-group">
{['Beijing', 'Shanghai', 'Guangzhou'].map((item) => (
<Radio key={item} value={item}>
{({ checked }) => (
<Button tabIndex={-1} shape="round" type={checked ? 'primary' : 'default'}>
{item}
</Button>
)}
</Radio>
))}
</Radio.Group>
{/* 卡片式自定义:选中时整卡高亮 */}
<Radio.Group name="card-radio-group">
{[1, 2].map((item) => (
<Radio key={item} value={item}>
{({ checked }) => (
<Space className={`custom-radio-card ${checked ? 'custom-radio-card-checked' : ''}`}>
<div className="custom-radio-card-mask">
<div className="custom-radio-card-mask-dot" />
</div>
<div>
<div className="custom-radio-card-title">Radio Card {item}</div>
<Typography.Text type="secondary">this is a text</Typography.Text>
</div>
</Space>
)}
</Radio>
))}
</Radio.Group>
</div>
);
};
对应的自定义样式(摘自仓库示例,演示如何基于 Arco 的 CSS 变量实现主题联动):
.custom-radio-card {
padding: 10px 16px;
border: 1px solid var(--color-border-2);
border-radius: 4px;
width: 250px;
box-sizing: border-box;
}
.custom-radio-card:hover,
.custom-radio-card-checked {
border-color: rgb(var(--primary-6));
}
.custom-radio-card-checked {
background-color: var(--color-primary-light-1);
}
input[name='card-radio-group']:focus-visible + .custom-radio-card {
box-shadow: 0 0 0 2px var(--color-primary-light-3);
}
实现细节有两个关键点:
- children 为函数时点击走"代理点击":为避免 children 中的表单元素干扰 label 触发 input 的 change,radio.tsx 会在
onLabelClick中e.preventDefault()并手动调用inputRef.current.click(); - 禁用态也可感知:2.66.14 起 children 函数增加
disabled参数,可在禁用状态下渲染不同内容(如置灰提示),类型定义见 interface.ts。
八、受控与非受控:一套状态逻辑贯穿全组件
Arco Design 的 Radio 与 Radio.Group 统一使用 useMergeValue.ts 实现"受控/非受控可无缝切换":
- 初始化:
value有值取value,否则取defaultValue,再否则取内置默认值; - 渲染值:外部
value非undefined时始终采用外部值(受控);为undefined时回落到内部 state(非受控); - 值回填:若外部
value从有值变为undefined(如移除受控属性),内部 state 自动同步,避免"半受控"状态下界面卡死。
结合 group.test.tsx 的"value control"用例可以直观理解:受控模式下点击第二项后 onChange 只上报新值,界面是否切换完全取决于外部是否用新 value 重新渲染。
此外,Radio 与 Radio.Group 都支持通过 ConfigProvider 的 componentConfig 配置全局默认属性(源码中通过 useMergeProps 合并 componentConfig?.Radio / componentConfig?.<a href="https://link.gitcode.com/i/4eb7f72686b0ff486b5eaeebfa6f5389" target="_blank">'Radio.Group'],见 [radio.tsx 与 group.tsx,机制见 useMergeProps.ts),适用于团队统一默认尺寸等场景。
九、无障碍、键盘交互与 RTL
- 原生语义:每个 Radio 内部渲染真实的
<input type="radio">,Group 容器带role="radiogroup"(见 group.tsx),name属性透传保证原生表单分组与屏幕阅读器语义; - 键盘焦点:input 通过绝对定位隐藏但保留焦点能力,
focus-visible时圆形指示器高亮背景(::before)或按钮内阴影(box-shadow: inset 0 0 0 2px)呈现焦点环(见 index.less); - RTL 支持:样式文件内置
.arco-radio-rtl/.arco-radio-group-rtl,对文本间距、圆点位置做了镜像处理(见 index.less); - 暗色模式:按钮选中态与容器底色在
<a href="https://link.gitcode.com/i/8ab9bf082e58c674cfb3482da6b35191" target="_blank">arco-theme='dark']下有独立 token 覆盖(见 [index.less)。
十、样式定制入口与版本演进
Radio 的所有视觉 token 集中在 token.less:圆点尺寸(14px)、边框宽度、悬停/禁用/选中的背景与文字色、按钮分割线宽度与间距(3px)、四种尺寸的行高等,均可通过主题变量(如 var(--color-primary-6)、var(--color-text-1))联动 Arco 全局主题。
从 更新日志 可以梳理出组件的演进脉络,这些也都是实际使用时的能力边界参考:
- 2.2.0:支持原生 HTML 标签属性透传;
- 2.29.0:支持函数式
children自定义节点; - 2.34.0:完善
children的 TypeScript 类型定义; - 2.51.0:修复
children为 0 时文本色异常; - 2.62.0:修复 Group 禁用后内部 Radio 单独禁用配置失效;
- 2.66.12:修复按钮类型 + 竖直方向排列失效问题;
- 2.66.14:children 函数新增
disabled参数。
结语
Arco Design 的 Radio 组件以"原生 input + 样式复刻"为底座,通过 RadioGroupContext 实现组内互斥,借助 useMergeValue 统一受控/非受控状态,配合函数式 children 可以低成本实现按钮式、卡片式等复杂形态。本文覆盖了 README.en-US.md 的全部 API 与仓库内全部示例(demo),如需深入验证行为,可继续阅读 radio.tsx、group.tsx 及其测试用例 index.test.tsx 与 group.test.tsx。