使用步骤

1创建一个函数 名称约定以with开头

2制定函数参数 参数应该以大写字母开头(作为要渲染的组件)

3在函数内部创建一个类组件 提供复用的状态逻辑代码 并返回

4在该组件中 渲染参数组件 同事将状态通过props传递给参数组件

 

//导入react
import React from 'react'
import ReactDOM from 'react-dom'

//导入组件
// 约定1:类组件必须以大写字母开头
// 约定2:类组件应该继承react.component父类 从中可以使用父类的方法和属性
// 约定3:组件必须提供render方法
// 约定4:render方法必须有返回值
import img from "./1.png"

//创建高阶组件
function withMouse(WrappedComponent){
class Mouse extends React.Component{

//鼠标状态
state={
x:0,
y:0
}
componentDidMount=()=>{
window.addEventListener('mousemove',this.handeleMove)
}
handeleMove=e=>{
this.setState({
x:e.clientX,
y:e.clientY
})
}
componentWillUnmount(){
window.removeEventListener('mousemove',this.handeleMove)
}
render(){
return <WrappedComponent {...this.state}></WrappedComponent>
}
}
return Mouse
}
const Position=props=>
(<p>鼠标当前位置:(x:{props.x},y:{props.y})</p>)

const Cat=props=>(
<img src={img} alt="猫"
style={{position:"absolute",
top:props.y,
left:props.x,
width:"100px",
height:"100px"}}/>
)



const MousePosition=withMouse(Position)
const CatPosition=withMouse(Cat)
class App extends React.Component {
constructor(props) {
super(props)
console.log('生命周期钩子函数:construtor')
}
//初始化state
//1进行dom操作
//2发送网络请求
render() {
console.log('生命周期钩子函数:render')
return (
<div id="title">
<h1>render props模式</h1>
<MousePosition></MousePosition>
<CatPosition></CatPosition>


</div>
)
}
}



ReactDOM.render(<App></App>, document.getElementById('root'))

运行结果

好客租房71-高阶组件使用步骤_ecmascript