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

使用步骤

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'))

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端大歌谣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值