当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React 高阶组件入门介绍

React 高阶组件入门介绍

2018年01月27日  | 移动技术网IT编程  | 我要评论

高阶组件的定义

hoc 不属于 react 的 api,它是一种实现模式,本质上是一个函数,接受一个或多个 react 组件作为参数,返回一个全新的 react 组件,而不是改造现有的组件,这样的组件被称为高阶组件。开发过程中,有的功能需要在多个组件类复用时,这时可以创建一个 hoc。

基本用法

包裹方式

const hoc = (wrappendcomponent) => {
 const wrappingcomponent = (props) => (
  <div classname="container">
   <wrappendcomponent {...props} />
  </div>
 );
 return wrappingcomponent;
};

上述代码中,接受 wrappendcomponent 作为参数,此参数就是将要被 hoc 包装的普通组件,在 render 中包裹一个 div,赋予它 classname 属性,最终产生的 wrappingcomponent 和 传入的 wrappendcomponent 是两个完全不同的组件。

在 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 组件,为新组件添加加载中的行为。

继承方式

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 中对组件的封装是按照最小可用单元的思想来进行封装的,理想情况下,一个组件只做一件事情,符合 oop 中的单一职责原则。如果需要对组件的功能增强,通过组合的方式或者添加代码的方式对组件进行增强,而不是修改原有的代码。

注意事项

不要在 render 函数中使用高阶组件

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

refs属性不能传递

hoc中指定的 ref,并不会传递到子组件,需要通过回调函数使用 props 传递。

参考链接


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网