【问题标题】:Pass props to HOC in typescript在 typescript 中将 props 传递给 HOC
【发布时间】:2020-01-26 05:58:13
【问题描述】:

我有一个布局 HOC 调用“withLayout”

interface WithLayoutProps {
  isHomePage?: boolean;
}

const withLayout = <P extends object>(Component: ComponentType<P>) => (
  props: P & WithLayoutProps,
): ReactElement => {

  return (
    <div>
      {!!isHomePage?<Header1 />:<Header2 />} //How the home page pass the "isHomePage" to there?
      <main>
        <Component {...props} />
      </main>
    </div>
  );
};

export default withLayout;

所有页面都是用这个组件布局的

const Home: NextPage = withLayout(() => {

  return (
    <div>home</div>
  )
})


但是在主页中,我们需要不同的标题,例如 &lt;Header1 /&gt; 和其他页面使用

如何将道具 isHomePage 传递给 withlayout

【问题讨论】:

  • 仅供参考,withLayout 不是 HOC。这只是一个函数。

标签: reactjs typescript high-order-component


【解决方案1】:

如何将道具 isHomePage 传递给 withlayout ?

只需将isHomePage 作为额外参数添加到 HOC。

withLayout 仍然是一个普通函数,因此您可以有更多或更少的参数(根据需要)。

const withLayout = <P extends object>(
  Component: ComponentType<P>,
  isHomePage: boolean = true // extra argument with default value
) => (
  props: P & WithLayoutProps,
): ReactElement => {...};

// usage:
const Home: NextPage = withLayout(
  () => (<div>home</div>)
})

const AboutUs: NextPage = withLayout(
  () => (<div>About Us</div>),
  false // not home page
)

【讨论】:

  • @DanaChen 所以你要求将isHomePage 属性传递给Header1Header2
猜你喜欢
  • 1970-01-01
  • 2020-11-19
  • 2018-10-24
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 2019-03-18
  • 2020-05-28
相关资源
最近更新 更多