React——react-router-dom V6 使用

1. 安装依赖

cnpm i -S react-router-dom@6

2. react-router-dom V6 属性:BrowserRouter 、Routes 、Route、Link .

import {BrowserRouter, Routes, Route, Link } from "react-router-dom"
function Index(){
    return <div>
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Link to="/page2">link</Link>} />
                <Route path="/page1" element={<Page1/>}/>
                <Route path="/page2" element={<Page2/>}/>
            </Routes>
        </BrowserRouter>
    </div>
}

3. 编程式跳转:useNavigate

1.必须在函数组件内使用
2.如果想要在类组件内使用,可以在外包装一层函数组件

函数组件使用

import {BrowserRouter, Routes, Route , useNavigate} from "react-router-dom"
function Index(){
    return <div>
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Button/>} />
                <Route path="/page1" element={<Page1/>}/>
                <Route path="/page2" element={<Page2/>}/>
            </Routes>
        </BrowserRouter>
    </div>
}

function Button(){
    const navigate = useNavigate()
    return <button onClick={()=>navigate("/page2")}>编程式跳转</button>
}

类组件使用

//Index.js
import {BrowserRouter, Routes, Route } from "react-router-dom"
class Index extends React.Component{
    render() {
        return (
            <div>
                <BrowserRouter>
                    <Routes>
                        <Route path="/page1" element={<NavigateComponent element={Page1} />} />
                        <Route path="/page2" element={<NavigateComponent element={Page2} />} />
                    </Routes>
                </BrowserRouter>
            </div>
        );
    }
}
/*NavigateComponent.js*/
import {useNavigate} from "react-router-dom"
function NavigateComponent(props){
    const navigate = useNavigate()
    return <div>
        <props.element navigate={navigate} />
    </div>
}
//Page1.js
class Page1 extends React.Component{
    render() {
        return <div>
            page1
            <button onClick={this.handleTo}>跳转2</button>
        </div>
    }

    handleTo =()=>{
        this.props.navigate("/page2")
    }
}

你可能感兴趣的:(React,react)