react 单选实现
实现 React 单选功能
在 React 中实现单选功能可以通过多种方式完成,以下是常见的几种方法:
使用受控组件(Controlled Component)
通过状态管理单选按钮的选中状态,适合表单场景:
import { useState } from 'react';
function RadioGroup() {
const [selectedOption, setSelectedOption] = useState('option1');
const handleChange = (e) => {
setSelectedOption(e.target.value);
};
return (
<div>
<label>
<input
type="radio"
value="option1"
checked={selectedOption === 'option1'}
onChange={handleChange}
/>
Option 1
</label>
<label>
<input
type="radio"
value="option2"
checked={selectedOption === 'option2'}
onChange={handleChange}
/>
Option 2
</label>
</div>
);
}
使用非受控组件(Uncontrolled Component)
利用 HTML 原生 radio 的互斥特性,适合简单场景:

function RadioGroup() {
return (
<div>
<label>
<input type="radio" name="options" value="option1" defaultChecked />
Option 1
</label>
<label>
<input type="radio" name="options" value="option2" />
Option 2
</label>
</div>
);
}
使用第三方库
对于复杂场景,可以使用如 react-radio-group 等专门库:
import { RadioGroup, Radio } from 'react-radio-group';
function MyRadioGroup() {
const [value, setValue] = useState('apple');
return (
<RadioGroup name="fruits" selectedValue={value} onChange={setValue}>
<Radio value="apple" /> Apple
<Radio value="orange" /> Orange
</RadioGroup>
);
}
自定义 Radio 组件

创建可复用的自定义 Radio 组件:
function CustomRadio({ value, checked, onChange, children }) {
return (
<label>
<input
type="radio"
value={value}
checked={checked}
onChange={onChange}
/>
{children}
</label>
);
}
function RadioGroup() {
const [selected, setSelected] = useState('A');
return (
<div>
<CustomRadio
value="A"
checked={selected === 'A'}
onChange={() => setSelected('A')}
>
Option A
</CustomRadio>
<CustomRadio
value="B"
checked={selected === 'B'}
onChange={() => setSelected('B')}
>
Option B
</CustomRadio>
</div>
);
}
样式优化技巧
为单选按钮添加自定义样式时,常用的 CSS 方案:
/* 隐藏原生 radio 用伪元素自定义样式 */
input[type="radio"] {
opacity: 0;
position: absolute;
}
input[type="radio"] + label::before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 8px;
border: 2px solid #ccc;
border-radius: 50%;
vertical-align: middle;
}
input[type="radio"]:checked + label::before {
background-color: #007bff;
border-color: #007bff;
}
无障碍访问建议
确保单选组符合 WAI-ARIA 规范:
<fieldset>
<legend>选择性别</legend>
<div role="radiogroup">
<input id="male" type="radio" name="gender" value="male" />
<label htmlFor="male">男性</label>
<input id="female" type="radio" name="gender" value="female" />
<label htmlFor="female">女性</label>
</div>
</fieldset>






