React 高阶组件装饰器写法

高阶组件

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

const withName = (Component) => { 
  const NewComponent = (props) => { 
    return ; 
  };
  return NewComponent; 
};

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


高阶链式调用

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

import React, { Component } from 'react' 
import { Button } from 'antd'
const withName = (Component) => {
  const NewComponent = (props) => { 
    return ; 
  };
  return NewComponent; 
};

const withLog = Component=>{
   class NewComponent extends React.Component{
     render(){
       return ; 
      }
      componentDidMount(){ 
        console.log('didMount',this.props) 
      }
    }
   return NewComponent
}
class App extends Component { 
    render() { 
      return ( 

hi,{this.props.name}

) } } 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 ; 
  };
  return NewComponent; 
};

const withLog = Component=>{
   class NewComponent extends React.Component{
     render(){
       return ; 
      }
      componentDidMount(){ 
        console.log('didMount',this.props) 
      }
    }
   return NewComponent
}
@withKaikeba 
@withLog
class App extends Component { 
    render() { 
      return ( 

hi,{this.props.name}

) } } export default App

你可能感兴趣的:(React 高阶组件装饰器写法)