1

我有一个布局 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 /> 和其他页面使用

我怎么能把道具传递isHomePagewithlayout?

4

1 回答 1

4

我怎样才能将道具 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
)
于 2019-09-26T02:13:20.483 回答