繁体   English   中英

如何在 react-router-dom 6 中使用 Route 元素作为变量/引用

[英]How to use Route element as a variable/reference in react-router-dom 6

假设我们有一个组件Home.jsx

const Home = () => {
  return (
    <div>
      <h1>Home</h1>
    </div>
  );
};
export default Home;

我们的路由器就像

const Router = () => (
  <>
    <Routes>
      <Route path="/" element={<Home />} />
    </Routes>
  </>
);

这很好用! 但是如果我们想在Route组件中导入如下element呢?

视图.js

export { default as Home } from "./home";

并修改我们的路线如下

import * as views from "../views";

<Routes>
    <Route path="/" element={views.Home} />
 </Routes>

这段代码产生以下错误:

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.

出路是什么?

好吧,我想出了一个解决方法,那就是使用变量作为方法。 这里是:

  <Route path="/" element={views.Home()} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM