美文网首页React JS让前端飞Web前端之路
React学习教程(8)React-Router基础

React学习教程(8)React-Router基础

作者: 四冶读史 | 来源:发表于2017-10-30 09:17 被阅读26次

概述

之前的所有代码都写在一个文件里(index.js),为了便于可读和管理,现在将单个功能写在对应的文件里,而要实现页面的跳转,就需要用到路由的功能,即,不同的URL对应不同的UI。
我们用基于React的路由库React-Router。安装和引用见上一篇文章《React学习教程(7)React-Router简介&安装》
下面且看如何配置路由。

创建BasicRouter.js文件

代码如下:

/**
 * 路由
 */
import React from 'react';
// import ReactDOM from 'react-dom';
import { HashRouter as Router, Route } from 'react-router-dom';

// 引入路由界面
import Main from './Main';
import Clock from './Clock';
import ExchangeRate from './ExchangeRate';

const BasicRouter = () => (
  <Router>
      <div>
        <Route exact path="/" component={Main} />
        <Route path="/clock" component={Clock} />
        <Route path="/exchangerate" component={ExchangeRate} /> 
      </div>     
  </Router>
);
export default BasicRouter;

1.真正用的路由库为react-router-dom,可通过npm install --save react-router-dom安装;
2.引入了3个路由界面,Main、Clock和ExchangeRate,如果后续需要,还可以添加;
3.加了“exact”关键字表示只匹配“/”,不然“/clock”等都会被匹配到;

修改index.js文件

代码如下:

import React from 'react';
import ReactDOM from 'react-dom';
import BasicRouter from './BasicRouter';
​
ReactDOM.render(
 <BasicRouter />
 ,document.getElementById('root')
);

将<BasicRouter />渲染到DOM

查看Main、Clock和ExchangeRate文件

Main:

/**
 * Main
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

function Welcome(props) {
    return <h1>welcome to {props.name} world!</h1>;
}

class Main extends Component{
    constructor(props) {
        super(props);
   }
​
    render(){
        return (
            <div>
                <Welcome name="React" />
            </div>
       );
   }
}
​
export default Main;

import时,只能import export default 后面的组件
Clock:

/**
 * Clock
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
​
function Welcome(props) {
    return <h1>hello, {props.name}</h1>;
}
​
class Clock extends Component{
    constructor(props) {
        super(props);
        this.state = {date: new Date()};
   }
​
    tick() {
        this.setState({
            date: new Date()
       });
   }
​
    componentDidMount(){
        // 装载定时器
        this.timerID = setInterval(
           () => this.tick(),
            1000
       );
   }

    componentWillUnmount(){
        // 卸载定时器
        clearInterval(this.timerID);
   }
​
    render(){
        return (
            <div>
                <Welcome name="world" />
                <h2>It is {this.state.date.toString('yyyy-MM-dd HH:mm:ss')}</h2>
            </div>
       );
   }
}

export default Clock;

ExchangeRate:

/**
 * 汇率
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
​
const MoneyTag = {
    Y: 'CNY',
    D: 'Dollar'
}

/**
 * Money组件
 */
class Money extends Component{
    constructor(props){
        super(props);
        //
   }
​
    /**
     * 输入金额切换状态
     * @param {*} e 
     */
    handle_change(e){
        this.props.handle_change(this.props.tag,e.target.value);
   }

    render(){
        const symbol = this.props.tag === 'Y' ? "Y" : "$";
        return(
            <div>
                <input type="text" value={this.props.num} onChange={(e) => {
                    this.handle_change(e);
               }} />{symbol}
            </div>
       );
   }
}

/**
 * 汇率组件
 */
class ExchangeRate extends Component{
    constructor(props){
        super(props);
        this.state = {
            tag: 'Y',
            num: ''
       }

        // 绑定this
        this.handle_change = this.handle_change.bind(this);
   }
​
    /**
     * 美元转换成人民币
     * @param {*} num 
     */
    to_cny(num){
        return num * 6.6392;
   }
​
    /**
     * 人民币转换成美元
     * @param {*} num 
     */
    to_dollar(num){
        return num * 0.1506;
   }
​
    /**
     * 汇率转换
     * @param {*} tag 
     * @param {*} num 
     */
    exchange_rate_change(tag,num){
        const input = parseFloat(num);
        if(Number.isNaN(input)){
            return '';
       }
        // 转换成美元
        if(tag === 'Y'){
            return Math.round(this.to_dollar(input) * 1000000) / 1000000;
       }
        // 转换成人民币
        return Math.round(this.to_cny(input) * 1000000) / 1000000;;
   }

    /**
     * 改变状态
     * @param {*} tag 
     * @param {*} num 
     */
    handle_change(tag,num){
        this.setState({
            tag: tag,
            num: num
       });
   }
​
    render(){
        const tag = this.state.tag;
        const num = this.state.num;
        const cny = tag === 'Y' ? num : this.exchange_rate_change(tag,num);
        const dollar = tag === 'D' ? num : this.exchange_rate_change(tag,num);
        return(
            <div>
                <Money tag='Y' num={cny} handle_change={this.handle_change} />
                <Money tag='D' num={dollar} handle_change={this.handle_change} />
            </div>
       );
   }
}

export default ExchangeRate;

至此,路由配置完
当,
浏览器输入localhost:3000/#/时,访问的是组件Main渲染的界面;
浏览器输入localhost:3000/#/clock时,访问的是组件Clock渲染的界面;
浏览器输入localhost:3000/#/exchangerate时,访问的是组件ExchangeRate渲染的界面;
至于URL中的“#”,可以参看上一篇文章《React学习教程(7)React-Router简介&安装》

注:
本教程相关的所以源码,可在https://github.com/areawen2GHub/reacttest.git下载

参考地址:
https://react-guide.github.io/react-router-cn/docs/guides/basics/RouteConfiguration.html

相关文章

网友评论

    本文标题:React学习教程(8)React-Router基础

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