如何精简React中根据条件渲染不同组件但传递相同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

