继承形式的高阶组件
采纳继承关联作为参数的组件和返回的组件,如果传进来的参数组件为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'@Dclass E extends Component { render() { return ( <div>我是E中div</div> ) }}export default E
创立一般组件F传入继承高阶组件D
import React, { Component } from 'react'import D from './D'@Dclass F extends Component { render() { return ( <p>我是F中p</p> ) }}export default F
最终实现如下成果:
2.操纵生命周期
首先在componentWillMount生命周期内打个log。
import React, { Component } from 'react'import D from './D'@Dclass 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...