Reactjs 在typescript中将道具传递给HOC

Reactjs 在typescript中将道具传递给HOC,reactjs,typescript,high-order-component,Reactjs,Typescript,High Order Component,我有一个关于布局的特别电话 interface WithLayoutProps { isHomePage?: boolean; } const withLayout = <P extends object>(Component: ComponentType<P>) => ( props: P & WithLayoutProps, ): ReactElement => { return ( <div> {!

我有一个关于布局的特别电话

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


但在主页中,我们需要不同的标题,如 和其他页面使用

如何将道具isHomePage传递到withlayout

如何将道具isHomePage传递到withlayout

只需将iHomePage作为额外参数添加到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
)
如何将道具isHomePage传递到withlayout

只需将iHomePage作为额外参数添加到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那么你是想将iHomePage道具传递给Header1或Header2吗?@DanaChen那么你是想将iHomePage道具传递给Header1或Header2吗?仅供参考,withLayout不是一个特别的问题。这只是一个函数。仅供参考,withLayout不是一个特殊的函数。这只是一个函数。