React 高阶组件装饰器写法

高阶组件

React里就有了HOC(Higher-Order Components)的概念
高阶组件也是一个组件,但是他返回另外一个组件,产生新的组件可以对属性进行包装,甚至重写部分生命周期

const withName = (Component) => { 
  const NewComponent = (props) => { 
    return <Component {...props} name="高阶组件" />; 
  };
  return NewComponent; 
};

上面withName组件,其实就是代理了Component,只是多传递了一个name参数


高阶链式调用

高阶组件还可以链式调用。

import React, { Component } from 'react' 
import { Button } from 'antd'
const withName = (Component) => {
  const NewComponent = (props) => { 
    return <Component {...props} name="高阶组件" />; 
  };
  return NewComponent; 
};

const withLog = Component=>{
   class NewComponent extends React.Component{
     render(){
       return <Component {...this.props} />; 
      }
      componentDidMount(){ 
        console.log('didMount',this.props) 
      }
    }
   return NewComponent
}
class App extends Component { 
    render() { 
      return ( <div className="App"> <h2>hi,{this.props.name}</h2> <Button type="primary">Button</Button> </div> ) 
    }
 }
export default withName(withLog(App))

高阶组件装饰器写法

  1. 安装插件: ES7装饰器可用于简化高阶组件写法
npm install --save-dev babel-plugin-transform-decorators-legacy
  1. 在项目的根目录下,新建config-overrides.js
cosnt { injexctBabelPlugin } = require('react-app-rewired');
module.exports = function override (config, env) {
  config = injectBabelPlugin(
    // 在默认的配置基础上注入
    // 插件名,插件配置
    ["import", {
      libraryName: "antd",
      libraryDirectory: "es",
      style: "css"
    }],
    config
  );
  config = injectBabelPlugin( 
    ['@babel/plugin-proposal-decorators', {
      "legacy": true 
    }], 
    config
  ) 
  return config;
}
  1. 使用装饰器
import React, { Component } from 'react' 

const withName = (Component) => {
  const NewComponent = (props) => { 
    return <Component {...props} name="高阶组件" />; 
  };
  return NewComponent; 
};

const withLog = Component=>{
   class NewComponent extends React.Component{
     render(){
       return <Component {...this.props} />; 
      }
      componentDidMount(){ 
        console.log('didMount',this.props) 
      }
    }
   return NewComponent
}
@withKaikeba 
@withLog
class App extends Component { 
    render() { 
      return ( <div className="App"> <h2>hi,{this.props.name}</h2>   
      <Button type="primary">Button</Button> </div> ) 
    }
 }
export default App
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 此文项目代码:https://github.com/bei-yang/I-want-to-be-an-archit...
    LM林慕阅读 148评论 0 1
  • 前言 Ract16后,想去官网看看有啥新的特性,无意间发现官网支持简体中文了,我是有多久没看了(以前学习害得我看繁...
    Kevin丶CK阅读 1,256评论 0 1
  • React进阶之高阶组件 前言 本文代码浅显易懂,思想深入实用。此属于react进阶用法,如果你还不了解react...
    流动码文阅读 1,193评论 0 1
  • 1. Decorator基本知识 在很多框架和库中看到它的身影,尤其是React和Redux,还有mobx中,那什...
    cbw100阅读 1,057评论 1 7
  • ReactDOM.createPortal(child, container):传送门。将子节点渲染到存在于父组件...
    hellomyshadow阅读 202评论 0 0