“路由器”不能用作 JSX 组件

use*_*642 8 javascript typescript reactjs react-router

错误信息

'Router' cannot be used as a JSX component.
  Its return type 'void' is not a valid JSX element.  TS2786

 import App from './App';
    5 | 
  > 6 | ReactDOM.render(<Router />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

索引.tsx 代码

ReactDOM.render(<Router />, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)

Router.tsx 代码

import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import App from './App';

export default function Routes() {
  <>
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={App} />
      </Switch>
    </BrowserRouter>
  </>;
}
Run Code Online (Sandbox Code Playgroud)

tsconfig

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    
  },
  "include": ["src"]
}

Run Code Online (Sandbox Code Playgroud)

这是什么错误?

index.tsx 中的错误<Router />

我该如何解决这个问题?

小智 8

我想发表评论,但我没有足够的声誉,但正如您的错误代码所示,您不会在Router.tsx. 尝试在 Router 函数中添加 return 语句,如下所示

export default function Routes() {
  return (
    <>
      <BrowserRouter>
        <Switch>
          <Route exact path="/" component={App} />
        </Switch>
      </BrowserRouter>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)


Sae*_*oja 6

    \n
  1. 返回 JSX 元素数组而不是单个元素。为了解决这个错误,我们必须使用 React 片段或 div 元素来包装数组。
  2. \n
  3. 从组件返回除 JSX 元素或 null 之外的任何值。
  4. \n
  5. 拥有过时版本的 React 类型。
  6. \n
\n
# \xef\xb8\x8f with NPM\nnpm install --save-dev @types/react@latest @types/react-dom@latest\n    \n# \xef\xb8\x8f if you also want to update react and react-dom\nnpm install react@latest react-dom@latest\n    \n# ------------------------------\n    \n# \xef\xb8\x8f with YARN\nyarn add @types/react@latest @types/react-dom@latest --dev\n    \n# \xef\xb8\x8f if you also want to update react and react-dom\nyarn add react@latest react-dom@latest\n
Run Code Online (Sandbox Code Playgroud)\n