React HOC(自用自用自用,笔记)

217 阅读1分钟

HOC higher order Comonent 高阶组件 

高阶组件不是组件,它是个函数。

比如我们登录页面有个注册和忘记密码的功能,都需要发送验证码这个功能。所以我们就用高阶组件将它这个功能抽离出来。

高阶组件: 是对各个组件中公共逻辑的一个抽象。

 1. 防止重复的代码 (页面复用)

 2. 条件渲染,控制组件的渲染逻辑(渲染劫持:就控制组件是否要渲染)

 3. 捕获| 劫持被处理的生命周期

纯函数:函数返回值之和它的参数有关,函数执行时不会对外部变量产生影响。

无状态: 组件不受state的影响。

上代码:

import React from 'react'const withMouse = (Component) => {    return class extends React.Component {        state = {x: 0, y: 0}        handleMouseMove = (event) => {          console.log(event)          this.setState({              x: event.clientX,              y: event.clientY          })        }        render () {            return (                <div  style={{height: '100vh'}} onMouseMove={this.handleMouseMove}>                    <Component {...this.props} mouse={this.state}/>                </div>            )        }    }}//定义一个纯函数无状态的组件const App = (props) => {    const { x , y } = props.mouse    return (        <div style={{height: '100vh'}}>            <h1> the mouse position is ({x}, {y})</h1>        </div>    ) }const AppWithMouse = withMouse(App)  //高阶组件替组件干活export default AppWithMouse

上面的withMouse就是一个高阶组件他为普通组件打工,也可以认为它可以加工一些普通组件,高阶组件能获取页面的鼠标的移动位置,高阶组件的数值通过解构和props可以给到组件 <Component {...this.props} mouse={this.state}/>。这就是一个高阶组件。