1.概念
高阶组件实际上是一个高阶函数,它接收一个组件作为参数,返回被包装的组件(这个传入的参数),并携带一些参数。
高阶组件内部往往会做一些逻辑处理,然后把这些处理后的逻辑数据传递出去。由此实现了组件逻辑的复用。
传入的参数组件来写不同的外部组件样式,实现了组件样式的多样化,逻辑的复用。
2.代码
import React, { useState, useEffect } from "react";
const getDisplayName = (differentComponent: any) => {
return differentComponent.displayName || differentComponent.name || 'component'
}
interface MouseProps {
status?: string
}
const WithCommonHoc = (WarppedComponend: any) => {
console.log('WarppedComponensssssssssssd', WarppedComponend)
console.log('status')
const Mouse: React.FC<MouseProps> = (props) => {
console.log('niuheng', props)
const [posX, setPosX] = useState(260)
const [posY, setPosY] = useState(80)
useEffect(() => {
window.addEventListener('mousedown', handelMouseDown)
window.addEventListener('mouseup', (e) => {
if (e.button === 0) {
window.removeEventListener('mousemove', handelMouseMove)
window.removeEventListener('mousedown', handelMouseMove)
window.removeEventListener('mouseup', (e) => { })
}
})
return () => {
window.removeEventListener('mousemove', handelMouseMove)
window.removeEventListener('mousedown', handelMouseDown)
}
}, [])
const handelMouseMove = (e: any) => {
setPosX((posX) => {
return posX = e.clientX
})
setPosY((posY) => {
return posY = e.clientY
})
}
const handelMouseDown = (e: any) => {
if (e.button === 0) {
window.addEventListener('mousemove', handelMouseMove)
}
}
Mouse.displayName = `WidthMouse${getDisplayName(WarppedComponend)}`
return (
<WarppedComponend x={posX} y={posY} {...props} />
)
}
return Mouse
}
export default WithCommonHoc
import React from "react";
interface mouseProps {
x?: number,
y?: number
}
interface MouseMoveComponent {
prefer: () => void
}
const MouseMove : React.FC<mouseProps> = ({
x,
y
}) => {
return <p>
当前鼠标位置:(x : {x} , y : {y})
</p>
}
export default MouseMove
import React from "react";
import { imgList } from '../../constant'
import cx from 'classnames'
import './index.css'
interface KaerProps {
x?: number,
y?: number,
status?: string
}
const Kaer: React.FC<KaerProps> = ({
x,
y,
status
}) => {
console.log('status', status)
setTimeout(() => {
console.log('打印定时器')
}, 1)
setImmediate(() => {
console.log('先来后到')
})
return (
<div>
{x && y && <img className={cx('imgstyle')} src={imgList[0]} alt="" style={{ left: x, top: y }} />}
</div>
)
}
export default Kaer
import React, { useState } from "react";
import MouseMove from '../component/MouseMove/index'
import WithCommonHoc from '../component/WithCommonHoc/index'
import Kaer from "../component/Kaer";
const Hoc: React.FC = () => {
const [testStatus, setTestStatus] = useState('niuheng')
const MousePosipotion = WithCommonHoc(MouseMove)
const MouseKaer = WithCommonHoc(Kaer)
console.log('WithCommonHoc', WithCommonHoc)
return (
<div>
<MousePosipotion />
<MouseKaer status={testStatus} />
</div>
)
}
export default Hoc