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

如何精简React中根据条件渲染不同组件但传递相同Props的重复代码?

Simplify Conditional Component Rendering with Shared Props

Great question! When you’re conditionally rendering two components but passing identical props to both, the key is to cut down on repetition by dynamically selecting your component first, then rendering it once with the shared props. Here’s a clean way to refactor your code:

Step 1: Dynamically select your component

First, create a variable that holds the component you want to render, based on your shouldRenderPlanA condition:

const LabelComponent = shouldRenderPlanA ? StyledLabelOptionOne : StyledLabelOptionTwo;

Step 2: Render the component with shared props

Now replace the conditional ternary inside your map with this single component, passing all shared props just once:

return (
  <>
    {options.map(option)}
    <StyledRow>
      {variousOptions.map((opt) => (
        <LabelComponent 
          variousProps={variousProps} 
          // Add any other shared props here once, not twice!
        />
      ))}
    </StyledRow>
  </>
);

Why this works

This approach eliminates duplicate prop code entirely. You only write your prop assignments once, and the component type swaps out based on your condition. It’s also easier to maintain—if you need to update or add props later, you only have to do it in one place instead of two.

Bonus: Handling minor prop differences (if needed later)

If you ever need to add small conditional variations to the props, you can extend this pattern with object spreading to keep things DRY:

// Base shared props
const baseProps = { variousProps: variousProps };

// Add conditional props if needed
const componentProps = shouldRenderPlanA 
  ? { ...baseProps, uniquePropForA: 'some-value' } 
  : { ...baseProps, uniquePropForB: 'another-value' };

const LabelComponent = shouldRenderPlanA ? StyledLabelOptionOne : StyledLabelOptionTwo;

// Render with combined props
<LabelComponent {...componentProps} />

This keeps your code clean while still allowing for flexibility when props aren’t 100% identical.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 15:52:46