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

需求描述,一个嵌套了很多层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);
相关推荐
西瓜太郎12341 天前
外层模型卡片与分组详情成功率不一致,应该怎么排查?
前端·typescript·go·软件工程·react
星辰徐哥2 天前
本地视频预览别只自己看:把Remotion动效项目发给客户远程验收
docker·ai·node.js·html·音视频·react·remotion
知兀3 天前
【前端】受控和非受控组件
前端·javascript·react
醉颜凉4 天前
React触摸事件全解析:掌握移动端交互开发的核心秘籍
react·前端开发·触摸事件·移动端交互·react事件
递归尽头是星辰4 天前
Java 智能体工程化:从 Spring AI 出发读懂 AgentScope
react·智能体·springai·javaai·agentscope
Richown7 天前
React 高级模式:并发渲染下的状态机驱动架构——从 Finite State Machine 到生产级实现
区块链·react
LayZhangStrive8 天前
Agent开发 - 实现人类与Manus智能体的终端窗口命令交互
ai·交互·agent·react·终端·manus
名字还没想好☜9 天前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js
ZGG00314 天前
真题拆解 05:ReAct 还是 Plan-and-Execute——规划范式怎么选
python·agent·react
eokred16 天前
图片预览组件的另一种设计:Headless、可组合、开箱即用
前端·react