Code Monkey home page Code Monkey logo

blog's People

Contributors

damiss avatar

blog's Issues

【2】React-Router的实际运用

React-Router的实际运用

此处采用React-Router 4.0
React Router DOM 已经 发布到 npm 因此你可以使用 npm 或者 yarn。

引用

react-routerreact-router-dom有什么区别?

React 的使用中,我们一般要引入两个包,reactreact-dom,那么 react-routerreact-router-dom 是不是两个都要引用呢?
非也,坑就在这里。他们两个只要引用一个就行了,不同之处就是后者比前者多出了 <Link> <BrowserRouter> 这样的 DOM 类组件。
因此我们只需引用 react-router-dom 这个包就行了

what's the diff between react-router-dom & react-route`?

基本使用方法

 /* Router.js */
import React, { Component } from 'react'
import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom'

import { Home } from './Home'
import { About } from './About'
import { Mine } from './Mine'

export default class Root extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        console.log(this.props)
        return (
            <div>
                <Router>
                    <div>
                        <ul>
                            <li><Link to="/">home</Link></li>
                            <li><Link to="/about">about</Link></li>
                            <li><Link to="/mine">mine</Link></li>
                        </ul>
                        <hr/>
                        <Route exact path="/" component={Home} />
                        <Route path="/about" component={About} />
                        <Route path="/mine" component={Mine} />
                    </div>
                    
                </Router>
            </div>
        )
    }
}

其次是页面组件

/* Home.js */
import React from 'react'
export function Home() {
    return (
        <div>
            <h1>Page Home </h1>
        </div>
    )
}

url与Component的匹配

react-router 根据 url 来判断加载相应的 Component 组件,其中,一般我们主页的 url 普遍都是 /,因此,需要在 <Route> 中加入 exact 关键字.作用为精确匹配 url.否则当地址为 localhost:300/about 时,会同时加载 Home 组件 和 About 组件.

在书写Router时要注意的一点是 <Router></Router> 标签内,只允许拥有一个子节点.如果包含多个子节点,项目就会报错.
A <Router> may have only one child element

Exclusive Routing

如果只想匹配一个route,可以使用 <Switch>

export default class Root extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        console.log(this.props)
        return (
            <div>
                <Router>
                    <div>
                        <ul>
                            <li><Link to="/">home</Link></li>
                            <li><Link to="/about">about</Link></li>
                            <li><Link to="/mine">mine</Link></li>
                        </ul>
                        
                        <hr/>
                        <Switch>
                            <Route exact path="/" component={Home} />
                            <Route path="/about" component={About} />
                            <Route path="/about/detail" component={Detail} />
                            <Route path="/mine" component={Mine} />
                        </Switch>
                    </div>
                </Router>
            </div>
        )
    }
}

const Detail = () => (
    <div>
        <h1>detail</h1>
    </div>
)

此时我们发现,组件并没有像我想象中的样子去渲染.尽管加上了 <Switch> 当我点击 /about/detail 时,仍然渲染的是 about 组件.这时,尝试一下,将 /about/detail
/about 互换一下.可以发现组件正常渲染.除此之外,还可以加上 exact,此时,就不用去关心 /about/about/detail 的前后位置.

Redirect

Rendering a will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
渲染一个<Redirect>导航到一个新的位置。 新位置将覆盖历史堆栈中的当前位置,例如服务器端重定向(HTTP 3xx)。

【1】CSS-Modules在React中的实践

React模块中书写CSS

在开发React的时候就发现这个问题,如何去组件化得管理CSS,而不是将CSS全局地引入到整个项目中,于是发现了CSS-Modules.

实际运用

项目由create-react-app构建
初始化项目后执行

npm run eject

将webpack配置文件导出,并找到 webpack.config.dev.js 中的 module 模块

{
    loader: require.resolve('css-loader'),
    options: {
          modules: true,   // 新增对css modules的支持
          localIdentName: '[name]__[local]__[hash:base64:5]', //设置文件编码
          importLoaders: 1,
    },
}

CSS-Modules书写方法

/* style.css */
.wrap {
    width: 100%;
    background: grey;
}
.banner {
    width: 1100px;
    margin: 0 auto;
    position: relative;
}
.bannerBox {
    width: 1100px;
    height: 420px;
}
.bannerBox img {
    width: 100%;
    height: 100%;
}
    /* Component.jsx */
    import styles from 'style.css'

    return `<div className=${styles.wrap}></div>`

styles.cssstyles 来引用,使用时就像用对象的方法去定义className

多个className如何共存

这里可以使用classnamesclassnames NPM

使用方法

import classNames from 'classnames'
/* style.css */
import styles from 'style.css'

class Example extends React.Component {
// ... 
  render () {
    var exClass = classNames({
      [styles.wrap]: true,
      [styles.banner]: this.state.isPressed,
    });
    return `<div className={exClass}>{this.props.label}</div>`;
  }
}

定义全局属性

:global(.add) {
    height: 100px;
    width: 100px
}

使用 :global 包裹 class 即可定义为全局class,这将不会解析.

如何复用样式

对于样式复用,CSS Modules 只提供了唯一的方式来处理:composes 组合

.root {
    border: 1px solid red
}
.child {
    composes: root;/* 复用的class */
    color: green; /* 自己的样式 */
}

生成的HTML为

<span class="demo__child__2M1Lg demo__root__2N9WP">span</span>

输入变量

CSS-Modules 支持使用变量,但是需要安装PostCSSpostcss-modules-values.在create-react-app脚手架中,已经预装好,可以直接用.

style.css中定义变量

@value blue: #0c77f8;
@value red: #ff0000;
@value green: #aaf200;

***.css中引用变量

@value colors: "./colors.css";
@value blue, red, green from colors;

.title {
  color: red;
  background-color: blue;
}

数组扁平化~

var arr = [1, [2, [3, 4]]];

function flatten(arr) {
    while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr);
    }
    return arr;
}

console.log(flatten(arr))
 [1, 2, 3, 4]

ES6 写法
...arr 扩展运算符一次只能展开一个嵌套
arr.som 中返回 arr 内的元素是否为数组, 如果是数组,则展开
while 判断 循环多次展开
最后输出[1,2,3,4]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.