2018年3月24日 星期六

react router 起步

react router 基本使用介紹




基本元件

Link
建立一個連結功能類似<a>
變更連結讓 router 重新渲染成其他元件

Route
設定這個元件讓 Switch 選擇要渲染的元件和傳遞參數

Switch
從網址作為連結去切換不同元件

Router

BrowserRouter
將設定的 Link Switch Route 等元件做連結


首先 先引入
babel 
react
react-dom
react-router
react-router-dom


<script src = "https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.2.0/react-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.2.2/react-router-dom.min.js"></script>   


將元件取出
 var BrowserRouter = ReactRouterDOM.BrowserRouter,
         Route= ReactRouterDOM.Route ,
         Link= ReactRouterDOM.Link ,
         Switch= ReactRouterDOM.Switch;




建立三個 component


class AboutMe extends React.Component
{
        render(){return (
        <div>
        <h1>About me</h1>
         </div>
        )};
 
}
class Page extends React.Component
{
        render(){return (
        <div>
        <h1>Page</h1>
         </div>
        )};
 
}

const Home = () => (
  <div>
    <h1>Hello world</h1>
  </div>
)

建立連結
const Main = () => (
  <main>
    <Switch>
      <Route exact path='/' component={Home}/>
      <Route path='/page' component={Page}/>
      <Route path='/AboutMe' component={AboutMe}/>

    </Switch>
  </main>
)

const Header = () => (
  <header>
    <nav>
      <ul>
        <li><Link to='/'>Home</Link></li>
        <li><Link to='/AboutMe'>AboutMe</Link></li>
        <li><Link to='/page'>Page</Link></li>
      </ul>
    </nav>
  </header>
)
由 Link 建立連結
Route 設定 path 切換不同 Component

將功能綁定對元件做連結
在 BrowserRouter 設定 basename
調整顯示的網址
如果未添加basename
https://de-yu.github.io/react-router/AboutMe => https://de-yu.github.io/AboutMe


const App = () => (
  <div>
    <Header />
    <Main />
  </div>
)
ReactDOM.render((
  <BrowserRouter basename="/react-router">
    <App />
  </BrowserRouter>
), document.getElementById('example'))

 example


沒有留言:

張貼留言