10.高阶组件

高阶组件

``` 目的:实现状态逻辑复用 采用:包装(装饰)模式,比如说:手机壳 手机:获取保护能力 手机壳:提供保护能力 高阶组件:就相当于手机壳,通过包装组件,增强组件功能 ```

思路分析

``` 高阶组件:(HOC,Higher-Order Component) 是一个函数,接收要包装的组件,返回增强后的组件 高阶组件内部创建一个类组件,在这个类组件中 提供复用的状态逻辑代码,通过prop 将复用的状态传递给被包装组件 WrappedComponent

const EnhancedComponent = withHOC(WrappedComponent)

//高阶组件内部创建的类组件:
class Mouse extends React.Component{
render(){
return <WrappedComponent {...this.state}>
}
}

<h2 style="color:red;">使用步骤</h2>

1.创建一个函数,名称约定以with 开头
2.指定函数参数,参数应该以大写字母开头(作为要渲染的组件)
3.在函数内部创建一个类组件,提供复用的状态逻辑代码,并返回
4.在该组件中,渲染参数组件,同时将状态通过prop传递给参数组件
5.调用高阶组件,传入要增强的组件,通过返回值拿到增强后的组件,并将其渲染到页面中

function withMouse(WrappedComponent){
class Mouse extends React.Component{}
return Mouse
}

//Mouse组件的render方法中:
return <WrappedComponent {...this.state} />

import PropTypes from 'prop-types'

import img from './images/33.jpeg'

//创建高阶组件
function withMouse(WrappedComponent){
//该组件提供的复用的状态逻辑
class Mouse extends React.Component{
//鼠标位置 state
state={
x:0,
y:0
}
//鼠标移动事件的事件处理程序
handleMouseMove = e => {
this.setState({
x:e.clientX,
y:e.clientY
})

}

    //监听鼠标移动事件
    componentDidMount(){
    window.addEventListener('mousemove',this.handleMouseMove)
    }
    //推荐在组件卸载时移除事件绑定
    componentWillUnmount(){
    window.removeEventListener('mousemove',this.handleMouseMove)
    }
    render(){
        return <WrappedComponent {...this.state} />
    }
    
}
return Mouse

}

//用来测试高阶组件
const Position = props =>(

鼠标当前位置:(x:{props.x},y: {props.y})

)

//猫抓老师的组件
const Cat = props =>(
<img src={img} alt="猫" style={{'100px;', height:'100px',position:'absolute',top:props.y-50,left:props.x-50}}>
)
//获取增强后的组件
const MousePosition = withMouse(Position)
const MouseCat = withMouse(Cat)

class App extends React.Component{
render(){
return(


高阶组件


{/* 渲染增强后的组件 */}



)
}

}

ReactDOM.render(,document.getElementById('root'))

<h2>设置displayName</h2>

使用高阶组件存在的问题:得到两个组件名称相同
原因:默认情况下,React 使用组件名称作为displayName
解决方法:为高阶组件 设置 displayName 便于调试时区分不同的组件
作用:用于设置调试信息(React Developer Tools信息)

//设置displayName
Mouse.displayName = WithMouse${getDisplayName(WrappedComponent)}
return Mouse

//function getDisplayName(WrappedComponent){
return WrappedComponent.displayName ||WrappedComponent.name || 'Component';
}

<h2>传递props</h2>

问题:props丢失
原因:高阶组件没有往下传递props
解决方式:渲染WrappedComponent 时,将state和this.props一起传递给组件

<WrappedComponent {...this.state} {...this.props}/>

原文地址:https://www.cnblogs.com/foreverLuckyStar/p/12250927.html