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

0次阅读

共计 1835 个字符,预计需要花费 5 分钟才能阅读完成。

继承形式的高阶组件

采纳继承关联作为参数的组件和返回的组件,如果传进来的参数组件为 WrappedComponent,那么返回中的组件将会继承于如果传进来的参数组件为 WrappedComponent。

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

代理形式的高阶组件

继承形式的高阶组件

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

1、继承形式的高阶组件继承于 React.Component, 而代理形式的高阶组件间接继承于传入的组件参数。
2、返回值也是显著不同的。继承形式的高阶组件须要把传入组件返回进来,而代理形式的高阶组件返回的是 super.render()。

继承形式的高阶组件的利用

其有两种操作:

1、操纵 props。
2、操纵生命周期。

1. 操纵 props
首先创立一个继承形式的高阶组件 D,通过以下办法实现操纵 props。

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 传入继承高阶组件 D

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

最终实现如下成果:

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

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

在控制台能够看到如下成果:

这个大家必定都是没问题,看的很明确。

上面咱们在继承高阶组件 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

在控制台能够看到如下成果:

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

结语

尽管本文具体介绍了继承高阶组件,然而 react 官网文档曾经不举荐大家去应用继承形式的高阶组件了。不要扭转原始组件,应用组合即为应该应用代理形式的高阶组件。
具体内容请观看官网解释:
https://zh-hans.reactjs.org/d…

正文完
 0