React的学习(七)——路由的简单使用

237 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第28天,点击查看活动详情

今天主要学习的是react中的路由的简单使用以及CSS的简单用法。

路由的使用

路由安装

在react中,路由使用也是需要先通过命令行进行安装的:

npm install --save-dev react-router-dom

配置路由

路由中相关的参数解释:

  • HashRouter:有#号
  • BrowserRouter:没有#号
  • Route:设置路由与组件关联
  • Switch:只要匹配到一个地址不往下匹配,相当于for循环里面的break
  • Link:跳转页面,相当于vue里面的router-link
  • exact:完全匹配路由
  • Redirect:路由重定向

引入路由

首先新建router.js文件,再新建两个页面,首页index和新闻页面news,导入到router.js中,

// index.js
import React from "react";
import { Link } from "react-router-dom";
class Index extends React.Component {
  render() {
    return (
      <div>
        <ul>
          <li>
            <Link to="/news">新闻页面</Link>
          </li>
        </ul>
      </div>
    );
  }
}
export default Index;

// router.js
import React, { lazy, Suspense } from "react";
import { HashRouter as Router, Route } from "react-router-dom";
const IndexPage = lazy(() => import("./pages/index"));
const NewsPage = lazy(() => import("./pages/news"));

class RouterComponent extends React.Component {
  render() {
    return (
      <React.Fragment>
        <Router>
          <React.Fragment>
            <Suspense fallback={<React.Fragment />}>
             // 首页
              <Route path="/" exact component={IndexPage}></Route>
              // 新闻页面
              <Route path="/news" exact component={NewsPage}></Route>
            </Suspense>
          </React.Fragment>
        </Router>
      </React.Fragment>
    );
  }
}

export default RouterComponent;

这里的代码只是简单的页面示例。

页面接受路由参数

在别的页面定义一个简单的事件传入参数:

 <li onClick={() => {
              this.props.history.push("/news/details?id=2&title=新闻详情3");}}>
            新闻详情3</li>

在details页面中,我们使用props来接受别的页面传入过来的参数

class NewsDetails extends React.Component {
  constructor(props) {
    super(props);
    // console.log(props.match.params);
  }
}

CSS的用法

CSS的内联样式

在react中,CSS的内联样式是需要用json格式来定义的,如果样式中间有短横线-,那就是使用驼峰式命名,例如font-size就用fontSize来命名:

<div style="{{width:'100px';height:'100px';fontSize:'20px'}}"></div>

class和className定义样式

在react中,不支持class,外部引用需要使用className。

<div className="name"></div>

如果需要使用传统的class来进行样式命名,那需要下载安装react-html-attrs插件:

npm install babel-plugin-react-html-attrs --save-dev