0

我有一个带有 React-Router 的高阶函数,但无法使其工作,无论是这种方式还是使用

return class extends React.Component { render{ ... }

export const withHeaderAndFooter = (component: ComponentType) => {
  return (
    <div className="flex flex-col h-full">
      <Header />
      {component}
      <Footer />
    </div>
  );
};


但这失败了:Type 'Element' is not assignable to type 'ComponentType<any>

import { withHeaderAndFooter } from "./layout";

// prettier-ignore
const App = () => {
  return (
    <Router>
        <Switch>
          <Route path="/" exact component={withHeaderAndFooter(Home)} />
          <Route path="/login" component={withHeaderAndFooter(Login)} />
          <Route path="*" component={NotFound} />
        </Switch>
    </Router>
  );
};

这失败了:index.js:1 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

const App = () => {
  return (
    <Router>
        <Switch>
          <Route path="/" exact component={() => withHeaderAndFooter(Home)} />
          <Route path="/login" component={() => withHeaderAndFooter(Login)} />
          <Route path="*" component={NotFound} />
        </Switch>
    </Router>
  );
};

我在用:

  • @types/react": "^17.0.5"
  • @types/react-dom": "^17.0.0"
  • 反应”:“^17.0.2”
  • 反应域”:“^17.0.2”
  • react-router-dom": "^5.2.0"

相关: HOC:类型“元素”不可分配给类型“FC<P>”

4

1 回答 1

1

您用于渲染组件的语法错误

export const withHeaderAndFooter = (component: ComponentType) => {
  return (
    <div className="flex flex-col h-full">
      <Header />
      {component} <- wrong syntax
      <Footer />
    </div>
  );
};

呈现组件的正确语法:

export const withHeaderAndFooter = (Component: ComponentType) => {
  return (
    <div className="flex flex-col h-full">
      <Header />
      <Component />
      <Footer />
    </div>
  );
};

请注意,变量名称的第一个字符必须为大写,以告知 JSX 解析器该变量是自定义 React 组件而不是 HTML 标记。

于 2021-05-23T10:28:30.033 回答