将重复的 React 代码转换为高阶组件 w/o 重复?

Convert duplicative React code into a Higher Order Component w/o duplication?

我有一些正在呈现内容的 React 代码。现在代码包含重复,因为如果代码包含号召性用语按钮,则代码应以一种方式呈现,如果道具中没有号召性用语按钮,则应以另一种方式呈现。我被要求尝试通过将代码转换为使用高阶组件 (HOC) 来消除重复,而我以前在 React 中没有做过这种类型的事情。我将如何通过使用 HOC 来减少重复?

  const hasCtaLinks = ctaLinks && ctaLinks.length > 0 ? true : false;

上面的代码是我写的,用来判断组件应该使用代码块A还是代码块B来渲染。在下面的代码中,leftText指的是传递给组件的内容。

这是代码块A:

{hasCtaLinks && (
    <>
      <LinkComponent
        className="mds-d-block"
        type="no-styles"
        //...other props here
      >
        {leftText && (
          <InnerComponent content={leftText || ""} />
        )}
      </LinkComponent>
      <CtaComponent ctaLinks={ctaLinks} />
    </>
  )}

这里是代码块 B,如果作为 prop 传递给组件的内容中没有 CTA,它就会呈现。

{!hasCtaLinks && leftText && (
    <InnerComponent content={leftText || ""} />
  )}

您可以看到代码块 B 只是代码块 A 中代码的重复。

我能够在不使用 HOC 的情况下解决这个问题。基本上只是在条件组件中传播 props.children,如下所示:

const ConditionalLink = (props: LinkProps) => {
  if (!props.href) {
    return <>{props.children}</>;
  }
  return <Link {...props}>{props.children}</Link>;
};

然后在上面的代码块A中替换为instead。