Reactjs:路由器的渲染道具无法工作 [英] Reactjs: render props of Router not working
本文介绍了Reactjs:路由器的渲染道具无法工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的项目没有收到任何错误,只是没有呈现任何内容。我错过了什么吗?
在App.js中,我使用渲染道具进行数据传输。
import "./App.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import Auth from "./views/Auth";
function App() {
return (
<div className="App">
<Router>
<Routes>
<Route
path="/login"
render={props => <Auth {...props} authRoute="login" />}
/>
<Route
path="/register"
render={props => <Auth {...props} authRoute="register" />}
/>
</Routes>
</Router>
</div>
);
}
export default App;
在Auth.js上获取,然后检查道具的值。
import React from "react";
import LoginForm from "../components/auth/LoginForm";
import RegisterForm from "../components/auth/RegisterForm";
const Auth = ({ authRoute }) => {
return (
<>
Learnit
{authRoute === "login" && <LoginForm />}
{authRoute === "register" && <RegisterForm />}
</>
);
};
export default Auth;
最后,我根据道具值呈现一个组件
import React from 'react'
const LoginForm = () => {
return (
<div>
<h1>Login</h1>
</div>
)
}
export default LoginForm
推荐答案
我看到您使用的是react-router-dom
v6.x。在RRDv6中,Route
道具不再接受render
或component
道具,而是接受一个element
道具,该道具接受要在path
上呈现的组件的JSX文本。
<Router>
<Routes>
<Route
path="/login"
element={<Auth authRoute="login" />}
/>
<Route
path="/register"
element={<Auth authRoute="register" />}
/>
</Routes>
</Router>
RouteProps接口
interface RouteProps { caseSensitive?: boolean; children?: React.ReactNode; element?: React.ReactElement | null; index?: boolean; path?: string; }
被路由的组件需要访问以前通过路由道具提供的内容,然后它们需要使用Reaction挂钩。
history
对象现在是useNavigate中的navigate
函数location
来自useLocationmatch
来自useMatch,或者如果您只需要路由匹配参数,则来自useParams。
这篇关于Reactjs:路由器的渲染道具无法工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文