继承方式的高阶组件
采用继承关联作为参数的组件和返回的组件,如果传进来的参数组件为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...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。