HoC 不属于 React 的 API,它是一种实现模式,本质上是一个函数,接受一个或多个 React 组件做为参数,返回一个全新的 React 组件,而不是改造现有的组件,这样的组件被称为高阶组件。开发过程当中,有的功能须要在多个组件类复用时,这时能够建立一个 Hoc。javascript
const HoC = (WrappendComponent) => {
const WrappingComponent = (props) => (
<div className="container"> <WrappendComponent {...props} /> </div> ); return WrappingComponent; }; 复制代码
上述代码中,接受 WrappendComponent 做为参数,此参数就是将要被 HoC 包装的普通组件,在 render 中包裹一个 div,赋予它 className
属性,最终产生的 WrappingComponent 和 传入的 WrappendComponent 是两个彻底不一样的组件。html
在 WrappingComponent 中,能够读取、添加、编辑、删除传给 WrappendComponent 的 props
,也能够用其它元素包裹 WrappendComponent,用来实现封装样式、添加布局或其它操做。前端
const HoC = (WrappedComponent, LoginView) => {
const WrappingComponent = () => {
const {user} = this.props;
if (user) {
return <WrappedComponent {...this.props} />
} else {
return <LoginView {...this.props} />
}
};
return WrappingComponent;
};
复制代码
上述代码中有两个组件,WrappedComponent 和 LoginView,若是传入的 props
中存在 user
,则正常显示的 WrappedComponent 组件,不然显示 LoginView 组件,让用户去登陆。HoC 传递的参数能够为多个,传递多个组件定制新组件的行为,例如用户登陆状态下显示主页面,未登陆显示登陆界面;在渲染列表时,传入 List 和 Loading 组件,为新组件添加加载中的行为。java
const HoC = (WrappendComponent) => {
class WrappingComponent extends WrappendComponent {
render() (
const {user, ...otherProps} = this.props;
this.props = otherProps;
return super.render();
}
}
return WrappingComponent;
};
复制代码
WrappingComponent 是一个新组件,它继承自 WrappendComponent,共享父级的函数和属性。可使用 super.render() 或者 super.componentWillUpdate() 调用父级的生命周期函数,可是这样会让两个组件耦合在一块儿,下降组件的复用性。react
React 中对组件的封装是按照最小可用单元的思想来进行封装的,理想状况下,一个组件只作一件事情,符合 OOP
中的单一职责原则。若是须要对组件的功能加强,经过组合的方式或者添加代码的方式对组件进行加强,而不是修改原有的代码。算法
render() {
// 每一次render函数调用都会建立一个新的EnhancedComponent实例
// EnhancedComponent1 !== EnhancedComponent2
const EnhancedComponent = enhance(MyComponent);
// 每一次都会使子对象树彻底被卸载或移除
return <EnhancedComponent />; } 复制代码
React 中的 diff
算法会比较新旧子对象树,肯定是否更新现有的子对象树或丢掉现有的子树并从新挂载。微信
// 定义静态方法
WrappedComponent.staticMethod = function() {/*...*/}
// 使用高阶组件
const EnhancedComponent = enhance(WrappedComponent);
// 加强型组件没有静态方法
typeof EnhancedComponent.staticMethod === 'undefined' // true
复制代码
HoC中指定的 ref
,并不会传递到子组件,须要经过回调函数使用 props
传递。app
关注微信公众号:创宇前端(KnownsecFED),码上获取更多优质干货!函数