【问题标题】:Per-page layout for pages wrapped with HOC using TypeScript使用 TypeScript 使用 HOC 包装的页面的每页布局
【发布时间】:2022-01-09 03:05:11
【问题描述】:

我想将布局应用到如下链接的页面:

layouts#per-page-layouts

但我的页面有所不同,它是用 HOC 包装的,所以我将getLayout 应用于高阶组件本身,如下所示:

PageWithAuth.getLayout

但它给了我这个错误:

页面如下所示:

function TestPage() {
  return {
    /** Your content */
  }
}

const PageWithAuth = withAuth(TestPage);

PageWithAuth.getLayout = function getLayout(page: ReactElement) {
  return (
      <Layout>{page}</Layout>
  )
}

export default PageWithAuth;

_app.tsx 看起来像这样:

type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

export default function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout ?? ((page) => page)

  return getLayout(<Component {...pageProps} />)
}

HOC 看起来像这样:

export function withAuth<P>(WrappedComponent: React.ComponentType<P>) {
  const ComponentWithAuth = (props: P) => {
    return <WrappedComponent {...props} />;
  };
  return ComponentWithAuth;
}

如何解决?

【问题讨论】:

  • 我相信 getLayout 类型在您的 HOC 中丢失了。您的 HOC 应该将 props 作为泛型并返回它们 - stackoverflow.com/a/65893770/15304814 - 此外,您可以通过为 getLayout 使用 React 的类型 FC 来简化一点。 { 组件 : { getLayout: FC }} & AppProps
  • withAuth 来自哪里?
  • @juliomalves 你是什么意思?它在一个简单的 tsx 文件中,我删除了实际代码并在此处对其进行了简化,但它的工作是将用户重定向到登录页面,如果用户未登录,您可以在此处查看示例项目 link

标签: typescript layout next.js higher-order-components


【解决方案1】:

您可以通过扩展React.FunctionComponent 并为其添加getLayout 属性来显式键入withAuth 的返回类型。

type WithAuthComponent<P> = React.FunctionComponent<P> & {
    getLayout?: (page: React.ReactElement) => React.ReactNode
}

export function withAuth<P = {}>(WrappedComponent: React.ComponentType<P>): WithAuthComponent<P> {
    const ComponentWithAuth = (props: P) => {
        // Your auth logic
        return <WrappedComponent {...props} />;
    }
    return ComponentWithAuth
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2016-01-08
    • 2021-07-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多