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

需求描述,一个嵌套了很多层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);
相关推荐
名字还没想好☜21 小时前
React setState 连续调用「丢更新」排查:批量更新与函数式更新
前端·javascript·react.js·react·usestate
sugar__salt21 小时前
DeepSeek-R1 WebGPU (1):在浏览器里跑大模型
react.js·reactjs·react·端模型
minhuan2 天前
大模型Agent核心架构,详解ReAct、Plan-and-Execute、Reason-Act-Observe循环21.6
react·大模型应用·agent架构·ai应用架构设计·plan-execute
名字还没想好☜2 天前
React useLayoutEffect vs useEffect:页面闪一下的元凶与正确修法
前端·javascript·react.js·react·hooks
钛态4 天前
前端安全防线:CSRF 攻击链路与双重 Token 校验的工程实现
前端·vue·react·web
钛态5 天前
AI 组件生成评测:别只看页面能不能渲染
前端·vue·react·web
赵大仁5 天前
Next.js + Vercel AI SDK 实战:30 分钟搭出流式 Chat 页面
前端·ai·实战·react·next.js·vercel
小小放舟、7 天前
PaiCLI-Demo:从零实现 ReAct Agent + Tool Call
java·后端·intellij-idea·springboot·agent·react·tool call
名字还没想好☜10 天前
React 受控与非受控组件:表单场景怎么选
前端·javascript·react.js·react·表单·受控组件
名字还没想好☜11 天前
Next.js 中间件实战:鉴权、重定向与 A/B 分流
开发语言·前端·javascript·中间件·react·next.js