今天這章會細說router 的用法
可以自動幫你產生href的連結
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router , Switch ,Route,useParams,Link} from 'react-router-dom';
const Child = () => {
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { idk } = useParams();
return (
<div>
<h3>ID: {idk}</h3>
</div>
);
}
const Routers = () => {
return(
<>
<Router>
<h2>Accounts</h2>
<ul>
<li>
<Link to="/netflix">Netflix</Link>
</li>
<li>
<Link to="/zillow-group">Zillow Group</Link>
</li>
<li>
<Link to="/yahoo">Yahoo</Link>
</li>
<li>
<Link to="/modus-create">Modus Create</Link>
</li>
</ul>
<Switch>
<Route path="/:idk" children={<Child />} />
</Switch>
</Router>
</>
);
}
ReactDOM.render(<Routers />, document.getElementById('root'));
這範例使用到
import {BrowserRouter as Router , Switch ,Route,useParams,Link} from 'react-router-dom';
BrowserRouter as Router <---這2個用法是一樣的,不管是用BrowserRouter還是Router一樣都不會抱錯
useParams() <---這是router 的參數,可取to="..."裡面的值
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router , Switch ,Route,Link,useRouteMatch} from 'react-router-dom';
const Routers = () => {
return(
<>
<Router>
<div>
<Optext optext={true} to="/" t_s="Home" />
<Optext to="/about" t_s="About" />
<hr />
<Switch>
<Route exact path="/" children={<Home />}/>
<Route path="/about" children={<About />} />
</Switch>
</div>
</Router>
</>
);
}
const Optext = ({ t_s, to, optext }) => {
let match = useRouteMatch({
path: to,
exact: optext
});
return (
<div className={match ? "active" : ""}>
{match && "go to --- >"}
<Link to={to}>{t_s}</Link>
</div>
);
}
const Home = () => {
return (
<div>
<h2>Home</h2>
</div>
);
}
const About = () => {
return (
<div>
<h2>About</h2>
</div>
);
}
ReactDOM.render(<Routers />, document.getElementById('root'));