企业为什么做网站推广,注册logo商标设计要求,app跨平台开发,物流商 网站建设方案一、什么是高阶组件
高阶组件#xff08; Higher-Order Component#xff0c;HOC #xff09;是一个以组件作为参数#xff0c;返回一个新组件的函数。
高阶组件最大的特点就是复用组件逻辑高阶组件本身并不是 React 的 API#xff0c;而是React组件的一种设计模式…一、什么是高阶组件
高阶组件 Higher-Order ComponentHOC 是一个以组件作为参数返回一个新组件的函数。
高阶组件最大的特点就是复用组件逻辑高阶组件本身并不是 React 的 API而是React组件的一种设计模式一种组件重用的高级技巧高阶组件是一个函数接收要包装的组件返回增强后的组件
二、如何实现一个高阶组件
高阶组件内部创建一个组件在这个组件中提供复用的状态逻辑代码通过props将复用状态传递给被包装组件 WrappedComponent
创建一个函数命名以 with 开头指定函数参数参数为组件所以参数应该以大写字母开头在函数内部创建一个组件提供复用的状态逻辑代码并返回在该组件中渲染参数组件同时将状态通过props传递给参数组件调用该高阶组件传入要增强的组件通过返回值拿到增强后的组件并将其渲染到页面中
function withMouse(WrappedComponent) {class Mouse extends React.Component {state {x: 0,y: 0,}render() {return (WrappedComponent {...this.state}/WrappedComponent)}}return Mouse
}const Position props (div鼠标位置 {props.x}, {props.y}/div
)const MousePosition withMouse(Position)MousePosition /三、高阶组件demo
代码
import React from react/*** 高阶组件*/// 获取组件名
// function getDisplayName(WrappedComponent) {
// return WrappedComponent.displayName || WrappedComponent.name || Component
// }// 创建高阶组件
function withMouse(WrappedComponent) {// 该组件提供复用的状态逻辑class Mouse extends React.Component {// 初始化statestate {x: 0,y: 0,}// 渲染UI可以将state和props 一起传递给组件render() {return (WrappedComponent {...this.state} {...this.props}/WrappedComponent)}// 组件挂载监听鼠标移动componentDidMount() {window.addEventListener(mousemove, this.handleMouseMove)}// 组件卸载移除监听componentWillUnmount() {window.removeEventListener(mousemove, this.handleMouseMove)}// 鼠标移动事件处理程序handleMouseMove e {this.setState({x: e.clientX,y: e.clientY,})}}// 设置displayName 这个为了调试区分用可以不设置// Mouse.displayName WithMouse${getDisplayName(WrappedComponent)}// 返回增强后的组件return Mouse
}// 位置组件用来测试高阶组件
const Position props (divh2鼠标位置: {props.x}, {props.y}/h2MousePosition组件: 接收的参数 a {props.a}/div
)// 猫抓老鼠组件用来测试高阶组件
const Cat props (divimgsrc{require(../../assets/images/cat.png)}alt猫height22pxstyle{{position: absolute,top: props.y - 10,left: props.x - 10,}}/MouseCat组件: 接收的参数 a {props.a}/div
)// 获取增强后的组件
const MousePosition withMouse(Position)
const MouseCat withMouse(Cat)// 使用
class MouseHigher extends React.Component {// 渲染增强后的组件render() {return (divMousePosition a111/MousePositionMouseCat a222/MouseCat/div)}
}export default MouseHigher
效果