将道具传递到打字稿中的HOC

时间:2019-09-26 02:03:47

标签: reactjs typescript high-order-component

我有一个布局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>
  )
})


但是在首页中,我们需要使用不同的标题,例如<Header1 /> 和其他页面使用

如何将道具isHomePage传递到withlayout

1 个答案:

答案 0 :(得分:3)

  

我如何将道具isHomePage传递给提款?

只需将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
)