美文网首页
React动态路由

React动态路由

作者: mwj610 | 来源:发表于2020-10-23 15:39 被阅读0次
    import React from 'react';
    import './App.css';
    import {BrowserRouter as Router,Switch,Route,Link} from 'react-router-dom'
    
    function Home() {
        return(
            <div>
                <Link to="/about" >to About</Link>
                <h1>Home</h1>
            </div>
    
        )
    }
    
    function About() {
        return(
            <div>
                <Link to="/" >to Home</Link>
                <h1>About</h1>
            </div>
    
        )
    }
    
    function News(props) {
        return(
            <h1>当前打开的是ID:{props.match.params.id}的新闻</h1>
        )
    }
    function NotFound(props) {
        let toIndex = () => {
            props.history.push('/')
        }
        return(
            <div>
                <h1>你访问的页面{props.location.pathname}找不到</h1>
                <button onClick={toIndex}>回到首页</button>
            </div>
    
        )
    }
    
    function App() {
        return(
            <div>
                <Router>
                    <Switch>
                        <Route path="/" exact component={Home}/>
                        <Route path="/about" exact component={About}/>
                        <Route path="/news/:id" exact component={News}/>
                        <Route path="/news/:id" exact component={About}/>
                        <Route  component={NotFound}/>
                    </Switch>
                </Router>
            </div>
        )
    }
    export default App;
    

    1.安装依赖npm install react-router-dom
    2.导入路由 import {BrowserRouter as Router,Switch,Route,Link} from 'react-router-dom'

    路由跳转:

    • <Link to="/about" >to About</Link>
    • props.history.push('/')

    相关文章

      网友评论

          本文标题:React动态路由

          本文链接:https://www.haomeiwen.com/subject/pqvvmktx.html