我需要在Map过程中传递一些 prop 给组件“Element”。
return <Route key={title} path={`/${path}`} element={Element} />
除了我无法将Element
属性转换为Tag组件(如
element={<Element />}
我将得到错误:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: <Cover />. Did you accidentally export a JSX literal instead of a component?
布线阵列文件:
const pagesData = [
{
title: "Cover",
Element: <Cover />,
path: "/",
},
{
title: "Welcome",
path: "/Welcome",
Element: <Welcome />,
},
];
export default pagesData;
React代码:
import {
Route,
Outlet,
Routes,
useNavigate,
useLocation,
} from "react-router-dom";
import pagesData from "./pagesData";
import { AnimatePresence } from "framer-motion";
const Router = (ChangePage) => {
const location = useLocation();
const pageRoutes = pagesData.map(
({ path, title, Element, nextPath, PreviousPath }) => {
return <Route key={title} path={`/${path}`} element={Element } />;
}
);
return (
// <AnimatePresence>
<Routes location={location} key={location.pathname}>
{pageRoutes}
</Routes>
// </AnimatePresence>
);
};
export default Router;
我的App.js代码:
import Router from "./router/index";
import "./App.scss";
import { useNavigate } from "react";
import React from "react";
const ChangePage = ({ pathname }) => {
const navigate = useNavigate();
navigate(pathname);
};
function App() {
if (true) {
return (
<div className="App">
<div className="desktop">
<Router ChangePage={ChangePage}></Router>
</div>
</div>
);
} else {
// <Mobile></Mobile>;
}
}
export default App;
触发从props传递的函数的第一个组件
import { React, useEffect, useState } from "react";
import { Route, Routes, useNavigate, useLocation } from "react-router-dom";
function Cover({ ChangePage, nextPath, PreviousPath, bgBolor }) {
const WheelHandler = (e) => {
if (e.deltaY > 0) {
try {
setTimeout(() => {
ChangePage({ pathname: nextPath });
}, 700);
} catch (error) {
console.log(error);
}
return;
} else {
}
};
return (
<div
className="page coverPage"
onWheel={WheelHandler}
style={{ backgroundColor: bgBolor }}
>
Cover
</div>
);
}
export default Cover;
1条答案
按热度按时间ctehm74n1#
您需要更新
pagesData
数组,以使用对要呈现的组件的引用,而不是JSX文本,这样您就可以在运行时*传递额外的props。useNavigate
挂接只能用于React组件。请将changePage
逻辑移到App
组件中,并将useNavigate
挂接移出回调。