[英]How to use Route element as a variable/reference in react-router-dom 6
Let's say we have a component Home.jsx
假设我们有一个组件
Home.jsx
const Home = () => {
return (
<div>
<h1>Home</h1>
</div>
);
};
export default Home;
and our router goes as我们的路由器就像
const Router = () => (
<>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</>
);
That's works fine!这很好用! But what if we want to import the
element
as below in the Route
component但是如果我们想在
Route
组件中导入如下element
呢?
views.js视图.js
export { default as Home } from "./home";
and modify our routes as follows并修改我们的路线如下
import * as views from "../views";
<Routes>
<Route path="/" element={views.Home} />
</Routes>
this piece of code makes following error:这段代码产生以下错误:
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.
What's the way out?出路是什么?
Well, I come up with a workaround, and that is use variable as method.好吧,我想出了一个解决方法,那就是使用变量作为方法。 Here it is:
这里是:
<Route path="/" element={views.Home()} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.