Reactjs:路由器的渲染道具不起作用

Lộc*_*ước 3 reactjs react-router-dom

我的项目没有出现任何错误,它只是不渲染任何内容。我错过了什么吗?

在 App.js 中,我使用 render props 进行数据传输。

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;
Run Code Online (Sandbox Code Playgroud)

我在 Auth.js 上获取它,然后检查 props 的值。

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;
Run Code Online (Sandbox Code Playgroud)

最后,我根据 props 的值渲染一个组件

import React from 'react'

const LoginForm = () => {
    return (
        <div>
            <h1>Login</h1>
        </div>
    )
}

export default LoginForm
Run Code Online (Sandbox Code Playgroud)

Dre*_*ese 5

我发现您使用的是react-router-domv6.x。在 RRDv6 中,Routeprops 不再采用render或componentprops,而是采用一个elementprop,该 prop 采用您想要在该 上渲染的组件的 JSX 文字path。

<Router>
  <Routes>
    <Route
      path="/login"
      element={<Auth authRoute="login" />}
    />
    <Route
      path="/register"
      element={<Auth authRoute="register" />}
    />
  </Routes>
</Router>
Run Code Online (Sandbox Code Playgroud)

路线与路线

路由属性接口

interface RouteProps {
  caseSensitive?: boolean;
  children?: React.ReactNode;
  element?: React.ReactElement | null;
  index?: boolean;
  path?: string;
}
Run Code Online (Sandbox Code Playgroud)

路由组件需要访问之前通过路由 props 提供的内容,然后它们需要使用 React hooks。