单选按钮

单选按钮是标准单选按钮元素的扩展,具有主题功能。


import { RadioButton } from 'primereact/radiobutton';
         

单选按钮用作具有 valuecheckedonChange 属性的受控输入。


<div className="flex flex-wrap gap-3">
    <div className="flex align-items-center">
        <RadioButton inputId="ingredient1" name="pizza" value="Cheese" onChange={(e) => setIngredient(e.value)} checked={ingredient === 'Cheese'} />
        <label htmlFor="ingredient1" className="ml-2">Cheese</label>
    </div>
    <div className="flex align-items-center">
        <RadioButton inputId="ingredient2" name="pizza" value="Mushroom" onChange={(e) => setIngredient(e.value)} checked={ingredient === 'Mushroom'} />
        <label htmlFor="ingredient2" className="ml-2">Mushroom</label>
    </div>
    <div className="flex align-items-center">
        <RadioButton inputId="ingredient3" name="pizza" value="Pepper" onChange={(e) => setIngredient(e.value)} checked={ingredient === 'Pepper'} />
        <label htmlFor="ingredient3" className="ml-2">Pepper</label>
    </div>
    <div className="flex align-items-center">
        <RadioButton inputId="ingredient4" name="pizza" value="Onion" onChange={(e) => setIngredient(e.value)} checked={ingredient === 'Onion'} />
        <label htmlFor="ingredient4" className="ml-2">Onion</label>
    </div>
</div>
         

可以使用值列表生成单选按钮。


{categories.map((category) => {
    return (
        <div key={category.key} className="flex align-items-center">
            <RadioButton inputId={category.key} name="category" value={category} onChange={(e) => setSelectedCategory(e.value)} checked={selectedCategory.key === category.key} />
            <label htmlFor={category.key} className="ml-2">{category.name}</label>
        </div>
    );
})}
         

variant 属性指定为 filled,以显示具有比默认 outlined 样式更高视觉强调的组件。


<RadioButton variant="filled" />
         

无效状态使用 invalid 属性显示,以指示验证失败。在与表单验证库集成时,可以使用此样式。


<RadioButton invalid/>
         

当存在 disabled 时,无法编辑和聚焦该元素。


<RadioButton checked disabled></RadioButton>
         

屏幕阅读器

单选按钮组件在内部使用隐藏的原生单选按钮元素,该元素仅对屏幕阅读器可见。用于描述组件的值可以通过与 inputId 属性结合使用的 label 标签提供,也可以使用 aria-labelledbyaria-label 属性。


<label htmlFor="rb1">One</label>
<RadioButton inputId="rb1" />

<span id="rb2">Two</span>
<RadioButton aria-labelledby="rb2" />

<RadioButton aria-label="Three" />
     

键盘支持

按键功能
tab将焦点移动到选中的单选按钮,如果组内没有选中的单选按钮,则第一个单选按钮接收焦点。
左箭头上箭头将焦点移动到上一个单选按钮,如果没有上一个单选按钮,则最后一个单选按钮接收焦点。
右箭头下箭头将焦点移动到下一个单选按钮,如果没有下一个单选按钮,则第一个单选按钮接收焦点。
空格如果聚焦的单选按钮未选中,则将其状态更改为选中。