React高阶组件HOC(三)继承方式的高阶组件

继承方式的高阶组件

采用继承关联做为参数的组件和返回的组件,若是传进来的参数组件为WrappedComponent,那么返回中的组件将会继承于若是传进来的参数组件为WrappedComponent。html

与代理方式的高阶组件的区别

代理方式的高阶组件
image.pngreact

继承方式的高阶组件
image.png数组

从以上两张图中能够看出有两点区别app

一、继承方式的高阶组件继承于React.Component,而代理方式的高阶组件直接继承于传入的组件参数。
二、返回值也是明显不一样的。继承方式的高阶组件须要把传入组件返回出去,而代理方式的高阶组件返回的是super.render()。

继承方式的高阶组件的应用

其有两种操做:this

一、操纵props。
二、操纵生命周期。

1.操纵props
首先建立一个继承方式的高阶组件D,经过如下方法实现操纵props。spa

import React from 'react'

const D = (WrappedComponent) => 
  class NewComp extends WrappedComponent {
    render() {
      // 获取继承而来的传入组件的元素内容
      const element = super.render()
      // 对元素标签判断添加样式属性
      const newStyle = {
        color:element.type === 'div' ? 'red' : 'yellow',
        fontSize: '50px'
      }
      // 定义新的props
      const newProps = {...this.props, style: newStyle}
      // React.cloneElement方法生成新的React对象
      return React.cloneElement(element, newProps, element.props.children)
    }
  }

export default D

建立普通组件E传入继承高阶组件D3d

import React, { Component } from 'react'
import D from './D'

@D
class E extends Component {
  render() {
    return (
      <div>我是E中div</div>
    )
  }
}

export default E

建立普通组件F传入继承高阶组件D代理

import React, { Component } from 'react'
import D from './D'

@D
class F extends Component {
  render() {
    return (
      <p>我是F中p</p>
    )
  }
}
export default F

最终实现以下效果:
image.pngcode

2.操纵生命周期
首先在componentWillMount生命周期内打个log。component

import React, { Component } from 'react'
import D from './D'

@D
class E extends Component {
  componentWillMount() {
    console.log('我是E中生命周期')
  }
  render() {
    return (
      <div>我是E中div</div>
    )
  }
}

export default E

在控制台能够看到以下效果:
image.png

这个你们确定都是没问题,看的很明白。

下面咱们在继承高阶组件D中输入一样内容:

import React from 'react'

const D = (WrappedComponent) => 
  class NewComp extends WrappedComponent {
    componentWillMount() {
      console.log('我是继承高阶组件D中生命周期')
    }

    render() {
      const element = super.render()
      const newStyle = {
        color:element.type === 'div' ? 'red' : 'yellow',
        fontSize: '50px'
      }
      const newProps = {...this.props, style: newStyle}
      return React.cloneElement(element, newProps, element.props.children)
    }
  }

export default D

在控制台能够看到以下效果:
image.png

哦吼,E中生命周期内容不见了,被继承高阶组件D给劫持了,这就是继承高阶组件操纵生命周期

结语

虽然本文详细介绍了继承高阶组件,可是react 官方文档已经不推荐你们去使用继承方式的高阶组件了。不要改变原始组件,使用组合即为应该使用代理方式的高阶组件。
详细内容请观看官网解释:
https://zh-hans.reactjs.org/d...

相关文章
相关标签/搜索