ihtml5 / blog

个人博客 源码阅读*前端实践 My Blog
MIT License
6 stars 0 forks source link

deep into react 之 高阶组件 #51

Open ihtml5 opened 7 years ago

ihtml5 commented 7 years ago

前言

高阶组件类似于函数式编程中的高阶函数,指的是向函数中传递一个react组件,函数将返回一个新的react组件。使用高阶组件我们可以很轻松地对原有组件进行进一步的抽象并同时保持原有组件的稳定性。

高阶组件的特性体现在两个地方:

  1. 属性代理
  2. 反向继承

属性代理

import React, { Component } from 'react';
const EnchanceComFactory = (wrappedComponent) => {
     return class extends Component {
         const newProps = {
               text: 'just do it'
          };
         render() {
             //  React.createElement(WrappedComponent, this.props, null)
              return <wrappedComponent {...this.props} {...newProps}/> 
        }
    }
}