在打字稿中将道具传递给 HOC
Pass props to HOC in typescript
我有一个布局 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>
)
})
但是在主页中,我们需要不同的 header,例如 <Header1 />
和其他页面使用
如何将道具 isHomePage
传递给 withlayout
?
How could I pass the props isHomePage to the 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
)
我有一个布局 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>
)
})
但是在主页中,我们需要不同的 header,例如 <Header1 />
和其他页面使用
如何将道具 isHomePage
传递给 withlayout
?
How could I pass the props isHomePage to the 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
)