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

需求描述,一个嵌套了很多层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);
相关推荐
一起学开源6 小时前
一文读懂 ReAct 范式:让 AI Agent 真正学会“思考+行动“
java·javascript·react.js·ecmascript·react·alibaba·智能体开发
格桑阿sir18 小时前
14-大模型智能体开发工程师:ReAct推理-行动框架
ai·大模型·llm·agent·react·智能体·推理模型
超级战斗鸡19 小时前
React Context Menu — 轻量级零依赖右键菜单组件
react
Richown3 天前
用 Three.js + React 打造一个赛博朋克风格的 3D 作品集页面
区块链·react
qcx235 天前
【系统学AI】08 Plan-then-Execute范式:先想好再做,比ReAct强在哪
前端·人工智能·react.js·ai·react·plan execute
JaydenAI6 天前
[MAF预定义ChatClient中间件-02]FunctionInvokingChatClient——实现ReAct循环和人机交互的大功臣
ai·人机交互·agent·react·hitl·maf·chatclient中间件
花月C8 天前
LangGraph 状态机与 ReAct Agent
python·agent·react·langgragh
Richown8 天前
密码学入门:区块链中的密码学原理
区块链·react
Richown8 天前
Web3钱包:钱包集成与签名验证
区块链·react
Richown9 天前
跨链桥接:多链资产转移实现
区块链·react