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

React Radio Button Group组件默认选中选项未按预期生效

自定义Radio Button Group默认选中值不生效问题排查与修复

问题描述

实现了一个可复用的Radio Button Group组件,期望通过父组件的useState设置默认选中第二个选项(Tea),但实际渲染时第一个选项(Coffee)始终被选中。父组件已设置:

const [selectedValue, setSelectedValue] = useState<String>(drinks[1].label);

但组件未按预期渲染默认选中项。

问题根源

RadioButtonGroup组件完全忽略了父组件的选中状态,同时存在两处关键错误:

  • 硬编码将第一个选项设为默认选中:defaultChecked={index === 0},完全不考虑外部传入的选中状态
  • 父组件未将selectedValue传递给RadioButtonGroup,且子组件未定义对应props接收该值
  • 错误使用非受控属性defaultChecked:父组件已维护状态,应使用受控属性checked来响应状态变化

修复方案

步骤1:修改RadioButtonGroup组件,支持接收选中状态

先更新组件的类型定义,添加selectedValue参数,再根据该值动态判断选项是否选中:

// 更新类型定义
interface IInputGroup {
  label: string;
  options: IOption[];
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  selectedValue: string; // 新增选中值参数
}

const RadioButtonGroup = ({ label, options, onChange, selectedValue }: IInputGroup) => {
  function renderOptions() {
    return options.map(({ label, name, disabled }: IOption) => {
      const shortenedOptionLabel = label.replace(/\s+/g, "");
      const optionId = `radio-option-${shortenedOptionLabel}`;

      return (
        <RadioButton
          value={label}
          label={label}
          key={optionId}
          id={optionId}
          name={name}
          disabled={disabled}
          checked={label === selectedValue} // 改用受控属性判断选中状态
          onChange={onChange}
        />
      );
    });
  }
  return (
    <Fieldset>
      <Legend>{label}</Legend>
      <Wrapper>{renderOptions()}</Wrapper>
    </Fieldset>
  );
};

export default RadioButtonGroup;

步骤2:父组件传递选中状态给RadioButtonGroup

在App组件中,将selectedValue作为props传递给RadioButtonGroup:

return (
  <PageLayout>
    <RadioButtonGroup
      label="Select your drink:"
      options={drinks}
      onChange={radioGroupHandler}
      selectedValue={selectedValue} // 传递选中状态
    />
  </PageLayout>
);

修复原理

  • 改为受控组件模式:通过父组件的selectedValue控制每个单选按钮的选中状态,确保组件状态与父组件完全同步
  • 移除硬编码逻辑:根据传入的selectedValue动态判断选中项,不再固定选中第一个选项
  • 使用受控属性checked替代非受控的defaultChecked,保证状态变化能实时反映到UI上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:06:49