// 如下代码实现了
// A中显示浏览器的高宽
// B中显示浏览器的高宽
import React, { useEffect, useState } from "react";
const WithShowBodySize = (Component) => {
const [xPos, setXPos] = useState('');
const [yPos, setYPos] = useState('');
const getPos = () => {
setXPos(document.body.offsetWidth)
setYPos(document.body.offsetHeight)
}
useEffect(() => {
console.log('WithShowBodySize')
getPos()
window.addEventListener('resize', getPos);
return() => {
window.removeEventListener('resize', () => {
console.log('resize监听事件已经移除')
});
}
}, [])
return (<>
<Component xPos={xPos}
yPos={yPos}></Component>
</>)
}
const ShowBodySizeA = (props) => {
return <div style={{ border: '1px solid red' }}>
{props?.xPos}-{props?.yPos}</div>
}
const ShowBodySizeB = (props) => {
return <div style={{ border: '3px solid green' }}>
{props?.xPos}-{props?.yPos}
</div>
}
const HOCDemo = (props) => {
const A = WithShowBodySize(ShowBodySizeA)
const B = WithShowBodySize(ShowBodySizeB)
useEffect(() => {
console.log('HOCDemo')
}, [])
return (<>
<br></br>
<br></br>
{A}
<br></br>
{B}
<br></br>
</>)
}
export default HOCDemo;
hooks实现的高阶组件demo
最新推荐文章于 2024-09-04 20:18:34 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)