我正在尝试在 React Js 中创建一个登录和注册页面,其想法是它们应该呈现在同一页面上,并且用户应该能够在它们之间切换(像这样 example )
我可以在组件之间创建切换功能(使用useState),但问题是我还需要根据用户的选择更改url(如果用户想登录,url应该是“/login”,如果登录)向上=>“/注册”)。我使用 React Router 为登录和注册创建了单独的组件,但它们在不同的页面上打开,我希望实现的是将它们放在同一个登录页面上。
import React from "react";
import "./styles.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Login from "./Login";
import SignUp from "./SignUp";
export default function App() {
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/">
<Login />
</Route>
<Route exact path="/sign-up" component={SignUp} />
</Switch>
</Router>
</div>
);
}
import React from "react";
import { Link } from "react-router-dom";
export default function Login() {
return (
<div style={{ display: "flex", flexDirection: "column" }}>
<div style={{ display: "flex", justifyContent: "space-evenly" }}>
<Link to="/">
<h1>Login</h1>
</Link>
<Link to="/sign-up">
<h1>Sign Up</h1>
</Link>
</div>
<form
style={{ display: "flex", flexDirection: "column", padding: "40px" }}
>
<input type="email" placeholder="email"></input>
<input type="password" placeholder="password"></input>
</form>
</div>
);
}
import React from "react";
export default function SignUp() {
return (
<div>
<form style={{display:"flex", flexDirection:"column", padding:"40px"}}>
<input type ="name" placeholder="Name"></input>
<input type ="email" placeholder="email"></input>
<input type ="password" placeholder="password"></input>
</form>
</div>
);
}
我对 React Js 相当陌生,所以我不知道这是否可能。我将不胜感激任何建议和帮助,谢谢。
最佳答案
首先,不要在登录组件中包含“登录”和“注册”链接。将它们移至您的 App.js。
App.js
<div className="App">
<Router>
<Switch>
<Route path="/">
<div style={{ display: "flex", justifyContent: "space-evenly" }}>
<Link to="/login">
<h1>Login</h1>
</Link>
<Link to="/sign-up">
<h1>Sign Up</h1>
</Link>
</div>
<Route exact path="/sign-up" component={SignUp} />
<Route exact path="/Login" component={Login} />
</Route>
</Switch>
</Router>
</div>
请注意 exact
在<Route exact path='/'>
必须删除,以便您可以在路由更改时切换并呈现“登录”或“注册”页面。您可以随时引用react-router tutorial .
对于登录组件,只需包含表单(就像您对注册组件所做的那样)就足够了。
已更新code sandbox
关于reactjs - 如何在同一页面上的2个组件之间切换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64708411/