react 安装路由模块_从零开始学习React-路由react-router配置(四)

c1a9feab0d9e2fbba0394a54519ea9f2.png

路由react-router可以实现根组件自动挂载其他不同的子组件,今天写一个路由的配置首先打开github搜索react-router,看一下上面有写好的示例,照葫芦画瓢即可:
https://reacttraining.com/react-router/web/example/basic

af1a429b29e18d8a8b33b0449434bb70.png
baf09b337a09d5526fcf1baf38f0a91f.png


具体步骤1:新建组件

在components文件夹底下新建3个组件页面,用于页面跳转路由的示例:
Home.js

import React, { Component } from 'react';class Home extends Component { constructor(props) { super(props); //react定义数据 this.state = {  } } render() { return ( 

我是Home组件界面

) }}export default Home;

New.js

import React, { Component } from 'react';class News extends Component { constructor(props) { super(props); //react定义数据 this.state = { } } render() { return ( 

我是News界面

) }}export default News;

About.js

import React from 'react';class About extends React.Component { //构造函数 constructor(props) { super(props); //react定义数据 this.state = { } } render() { return ( 

我是About界面

) }}export default About;

2:安装路由模块

打开终端,进入项目,输入安装路由模块的命令。

cnpm install react-router-dom --save
a9cfe6bd9031361c1ead3c27b705ab8f.png

3:引入路由模块

安装完成之后,在根组件App.js里面引入路由模块。

import {BrowserRouter as Router,Route,Link} from "react-router-dom";

4:路由代码

复制文档里面的路由配置的代码到根模块App.js里面。

 

5:引入前面面创建的3个组件

import Home from './components/Home';import About from './components/About';import News from './components/News';

到这一步的时候,路由配置完成了。

6:页面跳转标签

我们需要写个li标签,将跳转组件的路径写在里面。

  • Home
  • News
  • About

好了,现在可以测试一下了

52a6399fe6eb7231dabe23b36fcc55e5.gif

App.js参考代码

import React from 'react';import {BrowserRouter as Router,Route,Link} from "react-router-dom";//引入新建的组件import Home from './components/Home';import About from './components/About';import News from './components/News';function App() { return( 
Home News About
);}export default App;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值