一个滚动框高度动态计算解决方案

需求描述,一个嵌套了很多层div或者其他标签的内容框,而它的外层没有设置高度,或者使用百分比,而本容器需要设置高度来实现滚动,要么写死px高度,但是不能自适应,此时需要一个直系父容器(该容器要动态计算高度)包裹,这里的解决方法是,设计一个高阶方法,用于给本容器增加一个计算高度的父容器,并且超出高度隐藏内容。

php 复制代码
// 自定义高阶函数
// customizeHeightWrap.tsx"
import React, { useEffect, useState } from 'react';


export const customizeHeightWrap = (MyComponent: React.ComponentType<any>, minusHeight?: number) => {
// MyComponent为需要包裹的组件,minusHeight为参照父组件高度需要减去的高度(得到要滚动的高度)
    return function(props:any) {
        const [customHeight, setCustomHeight] = useState(500);
        useEffect(() => {
            window.addEventListener('resize', () => getClientHeight()); 
            getClientHeight(); 
            return () => {
            // 移除监听
            window.removeEventListener('resize', getClientHeight);
            };
        }, [])

        const getClientHeight = () => {
            try {
            const clientHeight = document.documentElement.clientHeight; // document.body.clientHeight
            const setHeight = clientHeight - (minusHeight || 0)
            setCustomHeight(setHeight);
            } catch (error) {}
        };
        return (
            <div className="customizeHeightWrap" style={{height: customHeight, overflowY: 'hidden'}}>
                <MyComponent {...props} />
            </div>
        );
    };
}
php 复制代码
// ScrollComponent.tsx 需要设置滚动的容器
import React, { useEffect, useState } from 'react';
import type { FC } from 'react';
import { customizeHeightWrap } from "@/components/customizeHeightWrap.tsx"
interface IProps = {
xxx: string;
...
}

const ScrollComponent: FC<IProps> = (props) => {
    return (
            <div style={{height: '100%, overScrollY: 'scroll'}}>
                超出高度滚动:这里100%参照父容器:高阶方法提供的包裹父组件
            </div>
        );
}
export default customizeHeightWrap(ScrollComponent);
相关推荐
全栈探索者1 天前
@Component + struct = 你的新函数组件——React 开发者的鸿蒙入门指南(第 2 期)
react·harmonyos·arkts·前端开发·deveco studio·鸿蒙next·函数组件
奔跑的呱呱牛2 天前
viewer-utils 图片预览工具库
javascript·vue·react
HetFrame2 天前
一种纯前端实现 Markdown 内容即时分享的思路
html·react·链接·markdown·工具
小浣熊喜欢揍臭臭3 天前
qiankun微服务搭建之【react+nextJs】
微服务·react
gentle coder5 天前
【langchain】agent部署的基础入门代码(持续更新中~)
python·langchain·react
RichardLau_Cx5 天前
【保姆级实操】MediaPipe SDK/API 前端项目接入指南(Web版,可直接复制代码)
前端·vue·react·webassembly·mediapipe·手部追踪·前端计算机视觉
小小工匠5 天前
大模型开发 - 零手写 AI Agent:深入理解 ReAct 模式与 Java 实现
人工智能·react
雪域迷影6 天前
MacOS中运行Next.js项目注册新用户时MongoDB报错MongoServerError
mongodb·macos·react·next.js
Highcharts.js6 天前
使用Highcharts与React集成 官网文档使用说明
前端·react.js·前端框架·react·highcharts·官方文档
im_AMBER9 天前
Web文件下载 : 从PDF预览Bug到Hook架构演进
前端·架构·react·浏览器·blob