zoukankan      html  css  js  c++  java
  • 对react的装饰器+HOC(高阶组件)应用

     高阶组件

              简单来说,高阶组件是一个函数,能够接受一个组件并返回一个新的组件。
              组件是将 props 转化成 UI ,然而 高阶组件将一个组价转化成另外一个组件。

    装饰器

            ES7中的一种语法糖,与Python中的装饰器使用及作用类似,其实就是以一种更为简洁的方式来来包装修改类的行为。装饰对象包括:类的属性类的方法

    项目中使用

    由于属于新特性,如果在项目中使用需要使用babel来进行转码。

    • 安装babel插件:

      Babel >= 7.x

    • Babel >= 7.x

        npm install --save-dev @babel/plugin-proposal-decorators

        Babel@6.x

        npm install --save-dev babel-plugin-transform-decorators-legacy

    .babelrc 配置:

    Babel >= 7.x

    { "plugins": [ ["@babel/plugin-proposal-decorators", { "legacy": true }], ] }

    Babel@6.x

    { "plugins": [ "transform-decorators-legacy" ] }

    import React, {Component} from 'react';

    const addDiv = (title) => (WrappedComponent) => class extends Component {
    render() {
    return (
    <div>
    <h1>{title}</h1>
    <hr/>
    <WrappedComponent/>>
    </div>
    )
    }
    };

    export default addDiv

    //demo.js

    import React, {Component} from 'react';
    import addDiv from './addDiv.js';

    @addDiv('标题')
    export default class Demo extends Component {
    ...
    render() {
    return(
    <i>demo</i>
    )
    }
    }

  • 相关阅读:
    modf()函数
    面向对象编程五大原则
    .Net网络资源
    整理CentOS常用命令
    在RHEL5上安装oracle10gLinux
    strchr()函数
    swab函数
    Strstr()函数
    tmpnam函数
    strdup ()函数
  • 原文地址:https://www.cnblogs.com/zhouyideboke/p/12626180.html
Copyright © 2011-2022 走看看