高阶函数与高阶组件
高阶函数,是一种特别的函数,接受的参数为函数,或者返回值也是函数
成立条件,二者兼一即可。
常见的高阶函数
a).定时器:setTimeout()/setInterval()
b).Promise:Promise(()=>{}) then(value=>{},reason=>{})
c).数组遍历相关的方法: forEach()/ filter()/ map()/ find()/ findindex()
d).fn.bind() 本身是个函数,bind方法返回一个新的函数方法
e).Form.create()() create函数能够包装组件,生成另外一个组件的新功能函数
f).getFieldDecorator()()
g).react-redux中的connect
高阶组件HOC
1 高阶组件就是接受一个组件作为参数并返回一个新组件的函数
2 高阶组件是一个函数,并不一个组件
注意,HOC 不会修改传入的组件,也不会使用继承来复制其行为。相反,HOC 通过将组件包装在容器组件中来组成新组件。HOC 是纯函数,没有副作用。被包装组件接收来自容器组件的所有 prop,同时也接收一个新的用于 render 的 prop。HOC 不需要关心数据的使用方式或原因,而被包装组件也不需要关心数据是怎么来的。
解决什么问题?
随着项目越来越复杂,开发过程中,多个组件需要某个功能,而且这个功能和页面并没有关系,所以也不能简单的抽取成一个新的组件,但是如果让同样的逻辑在各个组件里各自实现,无疑会导致重复的代码。
高阶组件总共分为两大类
代理方式
- 操纵prop
- 访问ref(不推荐)
- 抽取状态
- 包装组件
继承方式
- 操纵生命周期
- 操纵prop
代理方式之 操纵prop
删除prop
import React from 'react'
function HocRemoveProp(WrappedComponent) {
return class WrappingComPonent extends React.Component {
render() {
const { user, ...otherProps } = this.props;
return <WrappedComponent {...otherProps} />
}
}
}
export default HocRemoveProp;
增加prop
import React from 'react'
const HocAddProp = (WrappedComponent,uid) =>
class extends React.Component {
render() {
const newProps = {
uid,
};
return <WrappedComponent {...this.props} {...newProps} />
}
}
export default HocAddProp;
两个高阶组件的使用方法:
const newComponent = HocRemoveProp(SampleComponent);
const newComponent = HocAddProp(SampleComponent,'1111111');
以上是我目前了解到的,持续更新中