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

React组件基于三元条件追加JSX的代码精简重构方案咨询

重构方案

核心思路

把重复的公共结构全部保留,仅将两处差异点抽为动态变量,不需要拆分额外组件,也不会存在重复代码。

具体改动点

  1. 动态声明标签组件:根据renderPlanB的值选择要渲染的标签组件,避免重复写StyledRow的包裹逻辑
  2. 抽离RepeatingComponent的内部差异内容为单独变量,公共的errors和组件属性直接复用

重构后代码

// 差异点1:动态选择标签组件
const LabelComponent = renderPlanB ? StyledLabel : StyledLabelOptionTwo;

// 差异点2:抽离RepeatingComponent内部的条件内容
const repeatingInner = renderPlanB ? (
  <StyledContainer>
    <StyledProgress>{index + 2}</StyledProgress>
    <StyledEnteredCountries>
      {variousOptions.map(option)}
    </StyledEnteredCountries>
  </StyledWrappingContainer>
) : (
  <StyledRow>
    {variousOptions.map(option)}
  </StyledRow>
);

// 公共结构只写一次
return (
  <>
    {options.map(option)}
    <StyledRow>
      {variousOptions.map((opt) => (
        <LabelComponent
          variousProps={variousProps}
          variousProps={variousProps}
        />
      ))}
    </StyledRow>
    <RepeatingComponent
      variousProps={variousProps}
      variousProps={variousProps}
    >
      {errors}
      {repeatingInner}
    </RepeatingComponent>
  </>
);

方案优势

  • 所有公共逻辑仅保留一份,后续基础功能迭代只需要修改一处,不会出现同步问题
  • 差异点集中维护,后续扩展新的渲染分支时只需要修改对应变量即可
  • 完全符合不拆分独立组件的要求,组件整体逻辑依然内聚

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:15:03