您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在React中有关高阶组件详细介绍

2025/8/2 11:25:49发布22次查看
本篇文章主要介绍了react高阶组件入门介绍,这篇文章中我们详细的介绍了什么是高阶组件,如何使用高阶组件,现在分享给大家,也给大家做个参考。
高阶组件的定义
hoc 不属于 react 的 api,它是一种实现模式,本质上是一个函数,接受一个或多个 react 组件作为参数,返回一个全新的 react 组件,而不是改造现有的组件,这样的组件被称为高阶组件。开发过程中,有的功能需要在多个组件类复用时,这时可以创建一个 hoc。
基本用法
包裹方式
const hoc = (wrappendcomponent) => { const wrappingcomponent = (props) => ( <p classname="container"> <wrappendcomponent {...props} /> </p> ); return wrappingcomponent;};
上述代码中,接受 wrappendcomponent 作为参数,此参数就是将要被 hoc 包装的普通组件,在 render 中包裹一个 p,赋予它 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 传递。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
使用js如何实现循环nodelist dom列表
在vue中如何实现点击后文字变色
在vue-cli中如何实现为单独页面设置背景色
在vue中实现刷新和tab切换
以上就是在react中有关高阶组件详细介绍的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product