react--js实现界面跳转

react--js实现界面跳转

    • 引包
    • 使用
    • demo
    • 效果图

  • 学习资源推荐:https://blog.csdn.net/qq_42813491/article/details/90213353

引包

import { Redirect } from "react-router-dom";

使用

 <Redirect to="/home"/>

demo

  • Login.js
import React from 'react'
import { Redirect } from "react-router-dom";

class Login extends React.Component {

constructor(props){
    super(props);
    this.state={
        login:false
    }
}

    doLogin=()=>{
        let username=document.querySelector("input[type=text]").value;
        let password=document.querySelector("input[type=password]").value;
        if(username==="admin"&&password==="123456"){
            this.setState({
                login :true
            })
        }
    }

    
   
    render() {
        if(this.state.login){
           return  <Redirect to="/home"/>
        }else{
            alert("登录失败");
        }
        return (
            <div>

                <form onSubmit={this.doLogin}>
                    账号:<input type="text"/><br/>
                    密码:<input type="password"/><br/>
                    <input type="submit" value="登录"/>
                </form>
             
            </div>

        );
    }
}

export default Login;
  • App.js
import React from 'react';
import { BrowserRouter as Router, Route } from "react-router-dom";
import Login from './components/Login'
import Home from './components/Home'

class App extends React.Component {
  render() {

    return (
      <Router>
        <Route exact path="/" component={Login}  />
        <Route  path="/home" component={Home}  />
      </Router>
    );
  }
}

export default App;

  • Home.js
import React from 'react'
class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {  };
    }
    render() {
        return (
            <h1>这里是首页</h1>
        );
    }
}

export default Home;

效果图

在这里插入图片描述

  • 账号密码正确
    在这里插入图片描述
  • 账号或密码错误
    react--js实现界面跳转_第1张图片

你可能感兴趣的:(react)