[英]Conditionally adding more JSX to React component based on ternary statement
I currently have quite a complex (re-used component).我目前有一个相当复杂(重用的组件)。 I basically have a scenario whereby I use the value of
renderPlanB
(equates to true or false), and if true, we add various JSX elements.我基本上有一个场景,我使用
renderPlanB
的值(等于 true 或 false),如果为 true,我们添加各种 JSX 元素。 My current implementation looks like this but it repeats too much code.我当前的实现看起来像这样,但它重复了太多代码。 I don't want to make them separate components as changes to the base functionality would then need to be made in both.
我不想让它们成为单独的组件,因为需要在两者中对基本功能进行更改。 Any ideas on a clean re-factor?
关于干净的重构的任何想法?
return renderPlanB ? (
<>
{options.map(option)}
<StyledRow>
{variousOptions.map((opt) => (
<StyledLabel
variousProps={variousProps}
variousProps={variousProps}
/>
))}
</StyledRow>
<RepeatingComponent
variousProps={variousProps}
variousProps={variousProps}
>
{errors}
<StyledContainer>
<StyledProgress>{index + 2}</StyledProgress>
<StyledEnteredCountries>
{variousOptions.map(option)}
</StyledEnteredCountries>
</StyledWrappingContainer>
</RepeatingComponent>
</>
) : (
<>
{options.map(option)}
<StyledRow>
{variousOptions.map((opt) => (
<StyledLabelOptionTwo
variousProps={variousProps}
variousProps={variousProps}
/>
))}
</StyledRow>
<RepeatingComponent
variousProps={variousProps}
variousProps={variousProps}
>
{errors}
<StyledRow>
{variousOptions.map(option)}
</StyledRow>
</RepeatingComponent>
</>
);
As you can see, they both carry out the same logic, however, when renderPlanB
is true, we render some additional Styled Components.如您所见,它们都执行相同的逻辑,但是,当
renderPlanB
为 true 时,我们会渲染一些额外的样式化组件。
Contrived, but maybe try separating out...做作,但也许尝试分开......
return (
<>
<DefaultPlanComponents/>
{renderPlanB && <PlanBComponentsHere/>}
</>
)
I solved this issue by checking the renderPlanB
higher in the component tree (the component in the questions parent) so it looked like this:我通过检查组件树(问题父级中的组件)中更高的
renderPlanB
解决了这个问题,所以它看起来像这样:
{renderPlanB ? (
<NewComponent {...sharedProps} />
) : (
<DefaultComponent {...sharedProps} />
)}
I then just created a const of sharedProps
that I spread into both components (as they shared props) and this reduced the lines of code significantly:然后,我创建了一个由
sharedProps
组成的常量, sharedProps
其扩展到两个组件中(因为它们共享 props),这显着减少了代码行数:
const sharedProps = {
prop1: prop1,
prop2: prop2,
prop3: prop3,
prop4: prop4,
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.