簡體   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