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

当countryCode为US时设置Fitting默认选中值的实现方法

解决Fitting选项根据countryCode设置默认选中值的问题

需求与背景

  • 需求:当countryCode等于'US'时,Fitting选项默认选中'US';countryCode为'UK'时保持原有默认'UK'
  • 现有约束:
    • selectedOptions初始值为{Size: '14"', Fitting: 'UK'},用户手动选择选项后会更新该对象
    • countryCode仅取值'US'或'UK'

修改方案

核心是调整选中状态的判断逻辑:

  1. 优先保留用户已经选择的值(如果用户选过Fitting,不管countryCode是什么都用用户选的)
  2. 如果用户还没选择过Fitting,则根据countryCode来设置默认选中值
  3. 仅对Fitting选项生效,不影响其他选项(比如Size)

修改后的完整代码

export default function ProductOptionsDefault({
  name,
  values,
  countryCode,
}: Props) {
  const {setSelectedOption, selectedOptions} = useProductOptions();
  const handleChange = (optionName: string, optionValue: string) => {
    if (setSelectedOption) {
      setSelectedOption(optionName, optionValue);
    }
  };
  return (
    <fieldset key={name} className="mt-4">
      {/* Name */}
      <legend className="mb-3 text-sm font-medium text-dark">{name}</legend>

      <div className="flex flex-wrap items-center gap-2">
        {values.map((value) => {
          // 核心修改:调整选中状态判断逻辑
          let checked = selectedOptions?.[name] === value;
          // 仅对Fitting选项生效,且用户未手动选择时,根据countryCode设置默认
          if (name === 'Fitting' && !selectedOptions?.[name]) {
            checked = value === countryCode;
          }
          const id = `option-${name}-${value}`;
          return (
            <label key={id} htmlFor={id}>
              <input
                className="sr-only"
                type="radio"
                id={id}
                name={`option[${name}]`}
                value={value}
                checked={checked}
                onChange={() => handleChange(name, value)}
              />
              <OptionButton checked={checked} label={value} />
            </label>
          );
        })}
      </div>
    </fieldset>
  );
}

逻辑说明

  • 当用户已经选择过Fitting选项(selectedOptions?.['Fitting']存在值),则沿用用户的选择,不受countryCode影响
  • 当用户未选择过Fitting时,判断当前选项是否为Fitting,如果是则根据countryCode匹配对应的选项值,实现默认选中
  • 其他选项(比如Size)的原有逻辑保持不变,不受影响

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:55:27