解决流程
CommonLayout.tsx文件代码
const CommonLayout: NextPage = (props: any) => {
let { renderContent, nav,link } = props;
const footRef = useRef()
const [height, setHeight] = React.useState<number | string>(0)
//底部高度变化
const handleFooterHeight = () => {
//父级调用子级函数
let val = footRef.current.handleDivHeight();
setHeight(`calc(100vh - (${val+58}px))`)
}
useEffect(()=>{
handleFooterHeight()
// 监听窗口改变,执行handleFooterHeight
window.addEventListener("resize", handleFooterHeight);
// 销毁监听
return () => window.removeEventListener("resize", handleFooterHeight);
},[height])
return (
<>
{/*自定义函数组件,link是父级传给子级数据*/}
<G_Footer link={link} ref={footRef}/>
</>
)
}
G_Footer.tsx组件代码
const Footer: NextPage = forwardRef((props:any,ref: any) => {
let {link} = props;
useImperativeHandle(ref, () => ({
handleDivHeight:() => {
// 获取高度
return document.querySelector('.g-foot').offsetHeight;
}
}))
return (
<div className={"g-foot"}>
1111111111
</div >
)
})
特别注意
1.为什么css代码中calc的计算失效,请看我另外一篇文章
2.父级(函数组件)如何调用子级(函数组件)的函数,请看我另外一篇文章
个人网站:沉默博客
如有错误,请多多指教。
如对你有帮助,给个赞吧。