[英]Conditionally rendering components based on true or false prop
this should be a pretty straightforward question.这应该是一个非常简单的问题。 I have the following block of code:我有以下代码块:
return (
<StyledActiveOptions
className={classNames("lookup-active-options form-control", className)}
role="button"
tabIndex="0"
aria-haspopup="true"
aria-label={ariaActiveLabel}
isEnabled={!isDisabled && !isReadOnly}
onClick={onOpen}
onFocus={onFocus}
onKeyDown={onKeyDown}
>
{activeOptions.map((option) => (
<ChoiceOption
key={option.code}
option={option}
optionContentConfiguration={optionContentConfiguration}
isMultiple={isMultiple}
isRemovable={!isReadOnly && !isDisabled}
onRemove={onRemove}
renderIcon={renderIcon}
/>
))}
</StyledActiveOptions>
);
};
Basically, I want to re-factor this so that if renderIcon
is true - that we return <ChoiceOptionIcon />
component instead of just ChoiceOption />
& vice versa.基本上,我想重新考虑这一点,以便如果renderIcon
为 true - 我们返回<ChoiceOptionIcon />
组件而不是仅ChoiceOption />
,反之亦然。 I'm not entirely sure of the most efficient way of doing this that limits repeated code but ensure both components get all the props.我不完全确定限制重复代码但确保两个组件都获得所有道具的最有效方法。 Can anyone advise?任何人都可以建议吗?
When you are in a situation where you might have to render one of two different components passing the same (long list of) props, you can always replace:当您可能不得不渲染传递相同(长列表)道具的两个不同组件之一时,您始终可以替换:
import ChildComp1 from '/path';
import ChildComp2 from '/path';
const ParentComp = () => {
return condition
? <ChildComp1 prop1 prop2 ... propN />
: <ChildComp2 prop1 prop2 ... propN />
}
with:和:
import ChildComp1 from '/path';
import ChildComp2 from '/path';
const ParentComp = () => {
const ChildToRender = condition ? ChildComp1 : ChildComp2;
return <ChildToRender prop1 prop2 ... propN />
}
Something like this would work I presume我认为这样的事情会起作用
<StyledActiveOptions
className={classNames("lookup-active-options form-control", className)}
role="button"
tabIndex="0"
aria-haspopup="true"
aria-label={ariaActiveLabel}
isEnabled={!isDisabled && !isReadOnly}
onClick={onOpen}
onFocus={onFocus}
onKeyDown={onKeyDown}
>
{activeOptions.map((option) =>
option.renderIcon ? (
<div>Put a different component here</div>
) : (
<ChoiceOption
key={option.code}
option={option}
optionContentConfiguration={optionContentConfiguration}
isMultiple={isMultiple}
isRemovable={!isReadOnly && !isDisabled}
onRemove={onRemove}
renderIcon={renderIcon}
/>
)
)}
</StyledActiveOptions>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.