【问题标题】:Conditionally rendering components based on true or false prop基于 true 或 false prop 有条件地渲染组件
【发布时间】:2024-01-29 21:55:02
【问题描述】:

这应该是一个非常简单的问题。我有以下代码块:

  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>
  );
};

基本上,我想重新考虑这一点,以便如果 renderIcon 为真 - 我们返回 &lt;ChoiceOptionIcon /&gt; 组件而不仅仅是 ChoiceOption /&gt; ,反之亦然。我不完全确定限制重复代码但确保两个组件都获得所有道具的最有效方法。谁能给点建议?

【问题讨论】:

  • option =&gt; { const Comp = renderIcon ? ChoiceOptionIcon : ChoiceOption; return &lt;Comp ... /&gt;; }

标签: javascript reactjs conditional-operator


【解决方案1】:

我想这样的东西会起作用

 <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>

【讨论】:

  • OP 想要the most efficient way of doing this that limits repeated code,不是这个
  • 那么将我的答案插入StyledActiveOptions 组件就可以满足这个要求了吗?
  • 不确定你的意思;关键是你的&lt;div&gt;different&lt;/div&gt; OP 将插入具有完全相同的道具的&lt;ChoiceOptionIcon /&gt;,即大量重复的代码。请参阅我在问题下方的评论或其他答案,以了解避免这种情况的方法。
【解决方案2】:

当您可能需要渲染两个不同组件之一并传递相同的(长列表)道具时,您可以随时替换:

import ChildComp1 from '/path';
import ChildComp2 from '/path';

const ParentComp = () => {
  return condition
    ? <ChildComp1 prop1  prop2 ...  propN />
    : <ChildComp2 prop1  prop2 ...  propN />
}

与:

import ChildComp1 from '/path';
import ChildComp2 from '/path';

const ParentComp = () => {
  const ChildToRender = condition ? ChildComp1 : ChildComp2;
  return <ChildToRender prop1  prop2 ...  propN />
}

【讨论】: